/**
  * Returns the value of the field for the condition
  * For example: I want to check if age > 50, this function would return the 50
  *
  * @param object CRM_Civirules_TriggerData_TriggerData $triggerData
  * @return
  * @access protected
  * @abstract
  */
 protected function getFieldValue(CRM_Civirules_TriggerData_TriggerData $triggerData)
 {
     $entity = $this->conditionParams['entity'];
     $field = $this->conditionParams['field'];
     $data = $triggerData->getEntityData($entity);
     if (isset($data[$field])) {
         return $this->normalizeValue($data[$field]);
     }
     if (strpos($field, 'custom_') === 0) {
         $custom_field_id = str_replace("custom_", "", $field);
         try {
             $params['entityID'] = $data['id'];
             $params[$field] = 1;
             $values = CRM_Core_BAO_CustomValueTable::getValues($params);
             if (!empty($values[$field])) {
                 return $this->normalizeValue($values[$field]);
             } elseif (!empty($values['error_message'])) {
                 $custom_values = $triggerData->getCustomFieldValues($custom_field_id);
                 if (!empty($custom_values)) {
                     return $this->normalizeValue(reset($custom_values));
                 }
             }
         } catch (Exception $e) {
             //do nothing
         }
     }
     return null;
 }
 public function testCustomGroupMultipleOldFormat()
 {
     $contactID = $this->individualCreate();
     $customGroup = $this->customGroupCreate(array('is_multiple' => 1));
     $fields = array('custom_group_id' => $customGroup['id'], 'dataType' => 'String', 'htmlType' => 'Text');
     $customField = $this->customFieldCreate($fields);
     $params = array('entityID' => $contactID, "custom_{$customField['id']}" => 'First String');
     CRM_Core_BAO_CustomValueTable::setValues($params);
     $newParams = array('entityID' => $contactID, "custom_{$customField['id']}" => 1);
     $result = CRM_Core_BAO_CustomValueTable::getValues($newParams);
     $this->assertEquals($params["custom_{$customField['id']}"], $result["custom_{$customField['id']}_1"]);
     $this->assertEquals($params['entityID'], $result['entityID']);
     $this->customFieldDelete($customField['id']);
     $this->customGroupDelete($customGroup['id']);
     $this->contactDelete($contactID);
 }
 public function testCustomGroupMultipleOldFormate()
 {
     $params = array();
     $contactID = Contact::createIndividual();
     $customGroup = Custom::createGroup($params, 'Individual', TRUE);
     $fields = array('groupId' => $customGroup->id, 'dataType' => 'String', 'htmlType' => 'Text');
     $customField = Custom::createField($params, $fields);
     $params = array('entityID' => $contactID, "custom_{$customField->id}" => 'First String');
     $error = CRM_Core_BAO_CustomValueTable::setValues($params);
     $newParams = array('entityID' => $contactID, "custom_{$customField->id}" => 1);
     $result = CRM_Core_BAO_CustomValueTable::getValues($newParams);
     $this->assertEquals($params["custom_{$customField->id}"], $result["custom_{$customField->id}_1"]);
     $this->assertEquals($params['entityID'], $result['entityID']);
     Custom::deleteField($customField);
     Custom::deleteGroup($customGroup);
     Contact::delete($contactID);
 }
/**
 * File for the CiviCRM APIv3 group functions
 *
 * @package CiviCRM_APIv3
 * @subpackage API_pcpteams
 * @copyright CiviCRM LLC (c) 2004-2014
 */
function civicrm_api3_pcpteams_create($params)
{
    // since we are allowing html input from the user
    // we also need to purify it, so lets clean it up
    // $params['pcp_title']      = $pcp['title'];
    // $params['pcp_contact_id'] = $pcp['contact_id'];
    $htmlFields = array('intro_text', 'page_text', 'title');
    foreach ($htmlFields as $field) {
        if (!empty($params[$field])) {
            $params[$field] = CRM_Utils_String::purifyHTML($params[$field]);
        }
    }
    $entity_table = CRM_PCP_BAO_PCP::getPcpEntityTable($params['page_type']);
    $pcpBlock = new CRM_PCP_DAO_PCPBlock();
    $pcpBlock->entity_table = $entity_table;
    $pcpBlock->entity_id = $params['page_id'];
    $pcpBlock->find(TRUE);
    $params['pcp_block_id'] = $pcpBlock->id;
    $params['goal_amount'] = CRM_Utils_Rule::cleanMoney($params['goal_amount']);
    // 1 -> waiting review
    // 2 -> active / approved (default for now)
    $params['status_id'] = CRM_Utils_Array::value('status_id', $params, 2);
    // active by default for now
    $params['is_active'] = CRM_Utils_Array::value('is_active', $params, 1);
    $pcp = CRM_Pcpteams_BAO_PCP::create($params, FALSE);
    //Custom Set
    $customFields = CRM_Core_BAO_CustomField::getFields('PCP', FALSE, FALSE, NULL, NULL, TRUE);
    $isCustomValueSet = FALSE;
    foreach ($customFields as $fieldID => $fieldValue) {
        list($tableName, $columnName, $cgId) = CRM_Core_BAO_CustomField::getTableColumnGroup($fieldID);
        if (!empty($params[$columnName]) || !empty($params["custom_{$fieldID}"])) {
            $isCustomValueSet = TRUE;
            //FIXME: to find out the custom value exists, set -1 as default now
            $params["custom_{$fieldID}_-1"] = !empty($params[$columnName]) ? $params[$columnName] : $params["custom_{$fieldID}"];
        }
    }
    if ($isCustomValueSet) {
        $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params, $customFields, $pcp->id, 'PCP');
        CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_pcp', $pcp->id);
    }
    //end custom set
    $values = array();
    @_civicrm_api3_object_to_array_unique_fields($pcp, $values[$pcp->id]);
    return civicrm_api3_create_success($values, $params, 'Pcpteams', 'create');
}
Пример #5
0
 /**
  *Retrieve Name, Type and Id of record contain government value from customvalue table
  */
 static function retreiveContactFieldValue($contactID)
 {
     $govInfo = array();
     $govFieldId = self::retreiveContactFieldId('Identify');
     if (!empty($govFieldId) && $contactID) {
         $govValues = CRM_Core_BAO_CustomValueTable::getEntityValues($contactID, NULL, $govFieldId, TRUE);
         foreach ($govValues as $key => $val) {
             if ($val[$govFieldId['is_government']] == 1) {
                 $govInfo['type'] = $val[$govFieldId['Type']];
                 $govInfo['typeNumber'] = $val[$govFieldId['Number']];
                 $govInfo['key'] = $val[$govFieldId['is_government']];
                 $govInfo['id'] = ":{$key}";
                 break;
             }
         }
     }
     return $govInfo;
 }
Пример #6
0
 /**
  * Create() method with custom data.
  */
 public function testCreateWithCustomData()
 {
     $contactId = $this->individualCreate();
     //create custom data
     $customGroup = $this->customGroupCreate(array('extends' => 'Contribution'));
     $customGroupID = $customGroup['id'];
     $customGroup = $customGroup['values'][$customGroupID];
     $fields = array('label' => 'testFld', 'data_type' => 'String', 'html_type' => 'Text', 'is_active' => 1, 'custom_group_id' => $customGroupID);
     $customField = CRM_Core_BAO_CustomField::create($fields);
     $params = array('contact_id' => $contactId, 'currency' => 'USD', 'financial_type_id' => 1, 'contribution_status_id' => 1, 'payment_instrument_id' => 1, 'source' => 'STUDENT', 'receive_date' => '20080522000000', 'receipt_date' => '20080522000000', 'id' => NULL, 'non_deductible_amount' => 0.0, 'total_amount' => 200.0, 'fee_amount' => 5, 'net_amount' => 195, 'trxn_id' => '22ereerwww322323', 'invoice_id' => '22ed39c9e9ee6ef6031621ce0eafe6da70', 'thankyou_date' => '20080522');
     $params['custom'] = array($customField->id => array(-1 => array('value' => 'Test custom value', 'type' => 'String', 'custom_field_id' => $customField->id, 'custom_group_id' => $customGroupID, 'table_name' => $customGroup['table_name'], 'column_name' => $customField->column_name, 'file_id' => NULL)));
     $contribution = CRM_Contribute_BAO_Contribution::create($params);
     // Check that the custom field value is saved
     $customValueParams = array('entityID' => $contribution->id, 'custom_' . $customField->id => 1);
     $values = CRM_Core_BAO_CustomValueTable::getValues($customValueParams);
     $this->assertEquals('Test custom value', $values['custom_' . $customField->id], 'Check the custom field value');
     $this->assertEquals($params['trxn_id'], $contribution->trxn_id, 'Check for transcation id creation.');
     $this->assertEquals($contactId, $contribution->contact_id, 'Check for contact id for Conribution.');
 }
 /**
  * Returns the value of the field for the condition
  * For example: I want to check if age > 50, this function would return the 50
  *
  * @param object CRM_Civirules_TriggerData_TriggerData $triggerData
  * @return
  * @access protected
  * @abstract
  */
 protected function getFieldValue(CRM_Civirules_TriggerData_TriggerData $triggerData)
 {
     $entity = $this->conditionParams['entity'];
     $field = $this->conditionParams['field'];
     $data = $triggerData->getEntityData($entity);
     if (isset($data[$field])) {
         return $this->normalizeValue($data[$field]);
     }
     if ($this->isRelativeDate($field)) {
         $relativeDate = $this->parseRelativeDate($field);
         $field = $relativeDate['field'];
         $interval = $relativeDate['interval'];
         if (isset($data[$field])) {
             $date = new DateTime($data[$field]);
             $today = new DateTime("now");
             $diff = $date->diff($today);
             return $this->normalizeValue($diff->format('%' . $interval));
         }
     }
     if (strpos($field, 'custom_') === 0) {
         $custom_field_id = str_replace("custom_", "", $field);
         try {
             $params['entityID'] = $data['id'];
             $params[$field] = 1;
             $values = CRM_Core_BAO_CustomValueTable::getValues($params);
             $value = null;
             if (!empty($values[$field])) {
                 $value = $this->normalizeValue($values[$field]);
             } elseif (!empty($values['error_message'])) {
                 $value = $triggerData->getCustomFieldValue($custom_field_id);
             }
             if ($value !== null) {
                 $value = $this->convertMultiselectCustomfieldToArray($custom_field_id, $value);
                 return $this->normalizeValue($value);
             }
         } catch (Exception $e) {
             //do nothing
         }
     }
     return null;
 }
Пример #8
0
 /**
  * takes an associative array and creates a campaign object
  *
  * the function extract all the params it needs to initialize the create a
  * contact object. the params array could contain additional unused name/value
  * pairs
  *
  * @param array  $params (reference ) an assoc array of name/value pairs
  *
  * @return object CRM_Campaign_DAO_Campaign object
  * @access public
  * @static
  */
 static function create(&$params)
 {
     if (empty($params)) {
         return;
     }
     if (!CRM_Utils_Array::value('id', $params)) {
         if (!CRM_Utils_Array::value('created_id', $params)) {
             $session = CRM_Core_Session::singleton();
             $params['created_id'] = $session->get('userID');
         }
         if (!CRM_Utils_Array::value('created_date', $params)) {
             $params['created_date'] = date('YmdHis');
         }
         if (!CRM_Utils_Array::value('name', $params)) {
             $params['name'] = CRM_Utils_String::titleToVar($params['title'], 64);
         }
     }
     $campaign = new CRM_Campaign_DAO_Campaign();
     $campaign->copyValues($params);
     $campaign->save();
     /* Create the campaign group record */
     $groupTableName = CRM_Contact_BAO_Group::getTableName();
     if (isset($params['groups']) && !empty($params['groups']['include']) && is_array($params['groups']['include'])) {
         foreach ($params['groups']['include'] as $entityId) {
             $dao = new CRM_Campaign_DAO_CampaignGroup();
             $dao->campaign_id = $campaign->id;
             $dao->entity_table = $groupTableName;
             $dao->entity_id = $entityId;
             $dao->group_type = 'Include';
             $dao->save();
             $dao->free();
         }
     }
     //store custom data
     if (!empty($params['custom']) && is_array($params['custom'])) {
         CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_campaign', $campaign->id);
     }
     return $campaign;
 }
Пример #9
0
 /**
  * Takes an associative array and creates a participant object.
  *
  * @param array $params
  *   (reference ) an assoc array of name/value pairs.
  *
  * @return CRM_Event_BAO_Participant
  */
 public static function create(&$params)
 {
     $transaction = new CRM_Core_Transaction();
     $status = NULL;
     if (!empty($params['id'])) {
         $status = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant', $params['id'], 'status_id');
     }
     $participant = self::add($params);
     if (is_a($participant, 'CRM_Core_Error')) {
         $transaction->rollback();
         return $participant;
     }
     if (!CRM_Utils_Array::value('id', $params) || isset($params['status_id']) && $params['status_id'] != $status) {
         CRM_Activity_BAO_Activity::addActivity($participant);
     }
     //CRM-5403
     //for update mode
     if (self::isPrimaryParticipant($participant->id) && $status) {
         self::updateParticipantStatus($participant->id, $status, $participant->status_id);
     }
     $session = CRM_Core_Session::singleton();
     $id = $session->get('userID');
     if (!$id) {
         $id = CRM_Utils_Array::value('contact_id', $params);
     }
     // add custom field values
     if (!empty($params['custom']) && is_array($params['custom'])) {
         CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_participant', $participant->id);
     }
     //process note, CRM-7634
     $noteId = NULL;
     if (!empty($params['id'])) {
         $note = CRM_Core_BAO_Note::getNote($params['id'], 'civicrm_participant');
         $noteId = key($note);
     }
     $noteValue = NULL;
     $hasNoteField = FALSE;
     foreach (array('note', 'participant_note') as $noteFld) {
         if (array_key_exists($noteFld, $params)) {
             $noteValue = $params[$noteFld];
             $hasNoteField = TRUE;
             break;
         }
     }
     if ($noteId || $noteValue) {
         if ($noteValue) {
             $noteParams = array('entity_table' => 'civicrm_participant', 'note' => $noteValue, 'entity_id' => $participant->id, 'contact_id' => $id, 'modified_date' => date('Ymd'));
             $noteIDs = array();
             if ($noteId) {
                 $noteIDs['id'] = $noteId;
             }
             CRM_Core_BAO_Note::add($noteParams, $noteIDs);
         } elseif ($noteId && $hasNoteField) {
             CRM_Core_BAO_Note::del($noteId, FALSE);
         }
     }
     // Log the information on successful add/edit of Participant data.
     $logParams = array('entity_table' => 'civicrm_participant', 'entity_id' => $participant->id, 'data' => CRM_Event_PseudoConstant::participantStatus($participant->status_id), 'modified_id' => $id, 'modified_date' => date('Ymd'));
     CRM_Core_BAO_Log::add($logParams);
     $params['participant_id'] = $participant->id;
     $transaction->commit();
     // do not add to recent items for import, CRM-4399
     if (empty($params['skipRecentView'])) {
         $url = CRM_Utils_System::url('civicrm/contact/view/participant', "action=view&reset=1&id={$participant->id}&cid={$participant->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={$participant->id}&cid={$participant->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={$participant->id}&cid={$participant->contact_id}&context=home");
         }
         $participantRoles = CRM_Event_PseudoConstant::participantRole();
         if ($participant->role_id) {
             $role = explode(CRM_Core_DAO::VALUE_SEPARATOR, $participant->role_id);
             foreach ($role as &$roleValue) {
                 if (isset($roleValue)) {
                     $roleValue = $participantRoles[$roleValue];
                 }
             }
             $roles = implode(', ', $role);
         }
         $roleString = empty($roles) ? '' : $roles;
         $eventTitle = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $participant->event_id, 'title');
         $title = CRM_Contact_BAO_Contact::displayName($participant->contact_id) . ' (' . $roleString . ' - ' . $eventTitle . ')';
         // add the recently created Participant
         CRM_Utils_Recent::add($title, $url, $participant->id, 'Participant', $participant->contact_id, NULL, $recentOther);
     }
     return $participant;
 }
Пример #10
0
 /**
  * process the form after the input has been submitted and validated
  *
  * @access public
  * @return None
  */
 public function postProcess()
 {
     $params = $this->exportValues();
     $dates = array('receive_date', 'receipt_date', 'thankyou_date', 'cancel_date');
     if (isset($params['field'])) {
         foreach ($params['field'] as $key => $value) {
             $value['custom'] = CRM_Core_BAO_CustomField::postProcess($value, CRM_Core_DAO::$_nullObject, $key, 'Contribution');
             $ids['contribution'] = $key;
             foreach ($dates as $val) {
                 $value[$val] = CRM_Utils_Date::processDate($value[$val]);
             }
             if ($value['contribution_type']) {
                 $value['contribution_type_id'] = $value['contribution_type'];
             }
             if ($value['payment_instrument']) {
                 $value['payment_instrument_id'] = $value['payment_instrument'];
             }
             if ($value['contribution_source']) {
                 $value['source'] = $value['contribution_source'];
             }
             unset($value['contribution_type']);
             unset($value['contribution_source']);
             $contribution = CRM_Contribute_BAO_Contribution::add($value, $ids);
             // add custom field values
             if (CRM_Utils_Array::value('custom', $value) && is_array($value['custom'])) {
                 require_once 'CRM/Core/BAO/CustomValueTable.php';
                 CRM_Core_BAO_CustomValueTable::store($value['custom'], 'civicrm_contribution', $contribution->id);
             }
         }
         CRM_Core_Session::setStatus("Your updates have been saved.");
     } else {
         CRM_Core_Session::setStatus("No updates have been saved.");
     }
 }
Пример #11
0
 /**
  * takes an associative array and creates a contribution object
  *
  * @param array $params (reference ) an assoc array of name/value pairs
  * @param array $ids    the array that holds all the db ids
  *
  * @return object CRM_Contribute_BAO_Contribution object 
  * @access public
  * @static
  */
 static function &create(&$params, &$ids)
 {
     require_once 'CRM/Utils/Money.php';
     require_once 'CRM/Utils/Date.php';
     require_once 'CRM/Contribute/PseudoConstant.php';
     // FIXME: a cludgy hack to fix the dates to MySQL format
     $dateFields = array('receive_date', 'cancel_date', 'receipt_date', 'thankyou_date');
     foreach ($dateFields as $df) {
         if (isset($params[$df])) {
             $params[$df] = CRM_Utils_Date::isoToMysql($params[$df]);
         }
     }
     require_once 'CRM/Core/Transaction.php';
     $transaction = new CRM_Core_Transaction();
     $contribution = self::add($params, $ids);
     if (is_a($contribution, 'CRM_Core_Error')) {
         $transaction->rollback();
         return $contribution;
     }
     $params['contribution_id'] = $contribution->id;
     if (CRM_Utils_Array::value('custom', $params) && is_array($params['custom'])) {
         require_once 'CRM/Core/BAO/CustomValueTable.php';
         CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_contribution', $contribution->id);
     }
     $session =& CRM_Core_Session::singleton();
     if (CRM_Utils_Array::value('note', $params)) {
         require_once 'CRM/Core/BAO/Note.php';
         $noteParams = array('entity_table' => 'civicrm_contribution', 'note' => $params['note'], 'entity_id' => $contribution->id, 'contact_id' => $session->get('userID'), 'modified_date' => date('Ymd'));
         if (!$noteParams['contact_id']) {
             $noteParams['contact_id'] = $params['contact_id'];
         }
         CRM_Core_BAO_Note::add($noteParams, CRM_Utils_Array::value('note', $ids));
     }
     // check if activity record exist for this contribution, if
     // not add activity
     require_once "CRM/Activity/DAO/Activity.php";
     $activity = new CRM_Activity_DAO_Activity();
     $activity->source_record_id = $contribution->id;
     $activity->activity_type_id = CRM_Core_OptionGroup::getValue('activity_type', 'Contribution', 'name');
     if (!$activity->find()) {
         require_once "CRM/Activity/BAO/Activity.php";
         CRM_Activity_BAO_Activity::addActivity($contribution, 'Offline');
     }
     if (CRM_Utils_Array::value('soft_credit_to', $params)) {
         $csParams = array();
         if ($id = CRM_Utils_Array::value('softID', $params)) {
             $csParams['id'] = $params['softID'];
         }
         $csParams['pcp_display_in_roll'] = $params['pcp_display_in_roll'] ? 1 : 0;
         foreach (array('pcp_roll_nickname', 'pcp_personal_note') as $val) {
             if (CRM_Utils_Array::value($val, $params)) {
                 $csParams[$val] = $params[$val];
             }
         }
         $csParams['contribution_id'] = $contribution->id;
         $csParams['contact_id'] = $params['soft_credit_to'];
         // first stage: we register whole amount as credited to given person
         $csParams['amount'] = $contribution->total_amount;
         self::addSoftContribution($csParams);
     }
     $transaction->commit();
     // do not add to recent items for import, CRM-4399
     if (!CRM_Utils_Array::value('skipRecentView', $params)) {
         require_once 'CRM/Utils/Recent.php';
         require_once 'CRM/Contribute/PseudoConstant.php';
         require_once 'CRM/Contact/BAO/Contact.php';
         $url = CRM_Utils_System::url('civicrm/contact/view/contribution', "action=view&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home");
         $contributionTypes = CRM_Contribute_PseudoConstant::contributionType();
         $title = CRM_Contact_BAO_Contact::displayName($contribution->contact_id) . ' - (' . CRM_Utils_Money::format($contribution->total_amount, $contribution->currency) . ' ' . ' - ' . $contributionTypes[$contribution->contribution_type_id] . ')';
         $recentOther = array();
         if (CRM_Core_Permission::checkActionPermission('CiviContribute', CRM_Core_Action::UPDATE)) {
             $recentOther['editUrl'] = CRM_Utils_System::url('civicrm/contact/view/contribution', "action=update&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home");
         }
         if (CRM_Core_Permission::checkActionPermission('CiviContribute', CRM_Core_Action::DELETE)) {
             $recentOther['deleteUrl'] = CRM_Utils_System::url('civicrm/contact/view/contribution', "action=delete&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home");
         }
         // add the recently created Contribution
         CRM_Utils_Recent::add($title, $url, $contribution->id, 'Contribution', $contribution->contact_id, null, $recentOther);
     }
     return $contribution;
 }
Пример #12
0
 /**
  * Test case for deleteContact( ).
  */
 public function testDeleteContact()
 {
     $contactParams = $this->contactParams();
     $customGroup = $this->customGroupCreate();
     $fields = array('label' => 'testFld', 'data_type' => 'String', 'html_type' => 'Text', 'custom_group_id' => $customGroup['id']);
     $customField = CRM_Core_BAO_CustomField::create($fields);
     $contactParams['custom'] = array($customField->id => array(-1 => array('value' => 'Test custom value', 'type' => 'String', 'custom_field_id' => $customField->id, 'custom_group_id' => $customGroup['id'], 'table_name' => $customGroup['values'][$customGroup['id']]['table_name'], 'column_name' => $customField->column_name, 'file_id' => NULL)));
     //create contact
     $contact = CRM_Contact_BAO_Contact::create($contactParams);
     $contactId = $contact->id;
     //delete contact permanently.
     CRM_Contact_BAO_Contact::deleteContact($contactId, FALSE, TRUE);
     //Now check DB for location elements.
     //Now check DB for Address
     $this->assertDBNull('CRM_Core_DAO_Address', $contactId, 'id', 'street_address', 'Database check, Address deleted successfully.');
     //Now check DB for Email
     $this->assertDBNull('CRM_Core_DAO_Email', $contactId, 'id', 'email', 'Database check, Email deleted successfully.');
     //Now check DB for Phone
     $this->assertDBNull('CRM_Core_DAO_Phone', $contactId, 'id', 'phone', 'Database check, Phone deleted successfully.');
     //Now check DB for Mobile
     $this->assertDBNull('CRM_Core_DAO_Phone', $contactId, 'id', 'phone', 'Database check, Mobile deleted successfully.');
     //Now check DB for IM
     $this->assertDBNull('CRM_Core_DAO_IM', $contactId, 'id', 'name', 'Database check, IM deleted successfully.');
     //Now check DB for openId
     $this->assertDBNull('CRM_Core_DAO_OpenID', $contactId, 'id', 'openid', 'Database check, openId deleted successfully.');
     // Check that the custom field value is no longer present
     $params = array('entityID' => $contactId, 'custom_' . $customField->id => 1);
     $values = CRM_Core_BAO_CustomValueTable::getValues($params);
     $this->assertEquals(CRM_Utils_Array::value("custom_" . $customField->id, $values), '', 'Verify that the data value is empty for contact ' . $contactId);
     $this->assertEquals($values['is_error'], 1, 'Verify that is_error = 0 (success).');
     //Now check DB for contact.
     $this->assertDBNull('CRM_Contact_DAO_Contact', $contactId, 'id', 'sort_name', 'Database check, contact deleted successfully.');
     $this->quickCleanup(array('civicrm_contact', 'civicrm_note'));
     $this->customGroupDelete($customGroup['id']);
 }
Пример #13
0
 /**
  * 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}"));
     }
 }
Пример #14
0
 /**
  * takes an associative array and creates a petition signature activity
  *
  * @param array $params (reference ) an assoc array of name/value pairs
  *
  * @return object CRM_Campaign_BAO_Petition
  * @access public
  * @static
  */
 function createSignature(&$params)
 {
     if (empty($params)) {
         return;
     }
     if (!isset($params['sid'])) {
         $statusMsg = ts('No survey sid parameter. Cannot process signature.');
         CRM_Core_Session::setStatus($statusMsg, ts('Sorry'), 'error');
         return;
     }
     if (isset($params['contactId'])) {
         // add signature as activity with survey id as source id
         // get the activity type id associated with this survey
         $surveyInfo = CRM_Campaign_BAO_Petition::getSurveyInfo($params['sid']);
         // create activity
         // 1-Schedule, 2-Completed
         $activityParams = array('source_contact_id' => $params['contactId'], 'target_contact_id' => $params['contactId'], 'source_record_id' => $params['sid'], 'subject' => $surveyInfo['title'], 'activity_type_id' => $surveyInfo['activity_type_id'], 'activity_date_time' => date("YmdHis"), 'status_id' => $params['statusId'], 'activity_campaign_id' => $params['activity_campaign_id']);
         //activity creation
         // *** check for activity using source id - if already signed
         $activity = CRM_Activity_BAO_Activity::create($activityParams);
         // save activity custom data
         if (!empty($params['custom']) && is_array($params['custom'])) {
             CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_activity', $activity->id);
         }
         // set permanent cookie to indicate this petition already signed on the computer
         setcookie('signed_' . $params['sid'], $activity->id, time() + $this->cookieExpire, '/');
     }
     return $activity;
 }
Пример #15
0
 /**
  * Copy custom fields and attachments from an existing activity to another.
  *
  * @see CRM_Case_Page_AJAX::_convertToCaseActivity()
  *
  * @param array $params
  */
 public static function copyExtendedActivityData($params)
 {
     // attach custom data to the new activity
     $customParams = $htmlType = array();
     $customValues = CRM_Core_BAO_CustomValueTable::getEntityValues($params['activityID'], 'Activity');
     if (!empty($customValues)) {
         $fieldIds = implode(', ', array_keys($customValues));
         $sql = "SELECT id FROM civicrm_custom_field WHERE html_type = 'File' AND id IN ( {$fieldIds} )";
         $result = CRM_Core_DAO::executeQuery($sql);
         while ($result->fetch()) {
             $htmlType[] = $result->id;
         }
         foreach ($customValues as $key => $value) {
             if ($value !== NULL) {
                 // CRM-10542
                 if (in_array($key, $htmlType)) {
                     $fileValues = CRM_Core_BAO_File::path($value, $params['activityID']);
                     $customParams["custom_{$key}_-1"] = array('name' => $fileValues[0], 'path' => $fileValues[1]);
                 } else {
                     $customParams["custom_{$key}_-1"] = $value;
                 }
             }
         }
         CRM_Core_BAO_CustomValueTable::postProcess($customParams, 'civicrm_activity', $params['mainActivityId'], 'Activity');
     }
     // copy activity attachments ( if any )
     CRM_Core_BAO_File::copyEntityFile('civicrm_activity', $params['activityID'], 'civicrm_activity', $params['mainActivityId']);
 }
Пример #16
0
 public function testCustomGroupMultiple()
 {
     $params = array();
     $contactID = $this->individualCreate();
     $customGroup = $this->customGroupCreate();
     $fields = array('custom_group_id' => $customGroup['id'], 'data_type' => 'String', 'html_type' => 'Text');
     $customField = $this->customFieldCreate($fields);
     $params = array('entityID' => $contactID, 'custom_' . $customField['id'] . '_-1' => 'First String');
     $error = CRM_Core_BAO_CustomValueTable::setValues($params);
     $newParams = array('entityID' => $contactID, 'custom_' . $customField['id'] => 1);
     $result = CRM_Core_BAO_CustomValueTable::getValues($newParams);
     $this->assertEquals($params['custom_' . $customField['id'] . '_-1'], $result['custom_' . $customField['id']]);
     $this->assertEquals($params['entityID'], $result['entityID']);
     $this->customFieldDelete($customField['id']);
     $this->customGroupDelete($customGroup['id']);
     $this->contactDelete($contactID);
 }
Пример #17
0
 /**
  * Process the contribution
  *
  * @param $form
  * @param $params
  * @param $result
  * @param $contactID
  * @param $contributionType
  * @param bool $deductibleMode
  * @param bool $pending
  * @param bool $online
  *
  * @return CRM_Contribute_DAO_Contribution
  * @access public
  */
 static function processContribution(&$form, $params, $result, $contactID, $contributionType, $deductibleMode = TRUE, $pending = FALSE, $online = TRUE)
 {
     $transaction = new CRM_Core_Transaction();
     $className = get_class($form);
     $recurringContributionID = NULL;
     // add these values for the recurringContrib function ,CRM-10188
     $params['financial_type_id'] = $contributionType->id;
     //@todo - this is being set from the form to resolve CRM-10188 - an
     // eNotice caused by it not being set @ the front end
     // however, we then get it being over-written with null for backend contributions
     // a better fix would be to set the values in the respective forms rather than require
     // a function being shared by two forms to deal with their respective values
     // moving it to the BAO & not taking the $form as a param would make sense here.
     if (!isset($params['is_email_receipt'])) {
         $params['is_email_receipt'] = CRM_Utils_Array::value('is_email_receipt', $form->_values);
     }
     $recurringContributionID = self::processRecurringContribution($form, $params, $contactID, $contributionType, $online);
     $config = CRM_Core_Config::singleton();
     // CRM-11885
     // if non_deductible_amount exists i.e. Additional Details fieldset was opened [and staff typed something] -> keep it.
     if (isset($params['non_deductible_amount']) && !empty($params['non_deductible_amount'])) {
         $nonDeductibleAmount = $params['non_deductible_amount'];
     } else {
         //if ($contributionType->is_deductible && $deductibleMode) {
         if ($contributionType->is_deductible) {
             if ($online && isset($params['selectProduct'])) {
                 $selectProduct = CRM_Utils_Array::value('selectProduct', $params);
             }
             if (!$online && isset($params['product_name'][0])) {
                 $selectProduct = $params['product_name'][0];
             }
             // if there is a product - compare the value to the contribution amount
             if (isset($selectProduct) && $selectProduct != 'no_thanks') {
                 $productDAO = new CRM_Contribute_DAO_Product();
                 $productDAO->id = $selectProduct;
                 $productDAO->find(TRUE);
                 // product value exceeds contribution amount
                 if ($params['amount'] < $productDAO->price) {
                     $nonDeductibleAmount = $params['amount'];
                 } else {
                     $nonDeductibleAmount = $productDAO->price;
                 }
             } else {
                 $nonDeductibleAmount = '0.00';
             }
         } else {
             $nonDeductibleAmount = $params['amount'];
         }
     }
     $now = date('YmdHis');
     $receiptDate = CRM_Utils_Array::value('receipt_date', $params);
     if (!empty($form->_values['is_email_receipt'])) {
         $receiptDate = $now;
     }
     //get the contrib page id.
     $campaignId = $contributionPageId = NULL;
     if ($online) {
         $contributionPageId = $form->_id;
         $campaignId = CRM_Utils_Array::value('campaign_id', $params);
         if (!array_key_exists('campaign_id', $params)) {
             $campaignId = CRM_Utils_Array::value('campaign_id', $form->_values);
         }
     } else {
         //also for offline we do support - CRM-7290
         $contributionPageId = CRM_Utils_Array::value('contribution_page_id', $params);
         $campaignId = CRM_Utils_Array::value('campaign_id', $params);
     }
     // first create the contribution record
     $contribParams = array('contact_id' => $contactID, 'financial_type_id' => $contributionType->id, 'contribution_page_id' => $contributionPageId, 'receive_date' => CRM_Utils_Array::value('receive_date', $params) ? CRM_Utils_Date::processDate($params['receive_date']) : date('YmdHis'), 'non_deductible_amount' => $nonDeductibleAmount, 'total_amount' => $params['amount'], 'amount_level' => CRM_Utils_Array::value('amount_level', $params), 'invoice_id' => $params['invoiceID'], 'currency' => $params['currencyID'], 'source' => !$online || !empty($params['source']) ? CRM_Utils_Array::value('source', $params) : CRM_Utils_Array::value('description', $params), 'is_pay_later' => CRM_Utils_Array::value('is_pay_later', $params, 0), 'cancel_reason' => CRM_Utils_Array::value('cancel_reason', $params, 0), 'cancel_date' => isset($params['cancel_date']) ? CRM_Utils_Date::format($params['cancel_date']) : NULL, 'thankyou_date' => isset($params['thankyou_date']) ? CRM_Utils_Date::format($params['thankyou_date']) : NULL, 'campaign_id' => $campaignId);
     if (!$online && isset($params['thankyou_date'])) {
         $contribParams['thankyou_date'] = $params['thankyou_date'];
     }
     if (!$online || $form->_values['is_monetary']) {
         if (empty($params['is_pay_later'])) {
             $contribParams['payment_instrument_id'] = 1;
         }
     }
     if (!$pending && $result) {
         $contribParams += array('fee_amount' => CRM_Utils_Array::value('fee_amount', $result), 'net_amount' => CRM_Utils_Array::value('net_amount', $result, $params['amount']), 'trxn_id' => $result['trxn_id'], 'receipt_date' => $receiptDate, 'trxn_result_code' => CRM_Utils_Array::value('trxn_result_code', $result), 'payment_processor' => CRM_Utils_Array::value('payment_processor', $result));
     }
     if ($recurringContributionID) {
         $contribParams['contribution_recur_id'] = $recurringContributionID;
     }
     $contribParams['contribution_status_id'] = $pending ? 2 : 1;
     $contribParams['is_test'] = 0;
     if ($form->_mode == 'test') {
         $contribParams['is_test'] = 1;
     }
     $ids = array();
     if (isset($contribParams['invoice_id'])) {
         $contribID = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $contribParams['invoice_id'], 'id', 'invoice_id');
         if (isset($contribID)) {
             $ids['contribution'] = $contribID;
             $contribParams['id'] = $contribID;
         }
     }
     //create an contribution address
     if ($form->_contributeMode != 'notify' && empty($params['is_pay_later']) && !empty($form->_values['is_monetary'])) {
         $contribParams['address_id'] = CRM_Contribute_BAO_Contribution::createAddress($params, $form->_bltID);
     }
     // CRM-4038: for non-en_US locales, CRM_Contribute_BAO_Contribution::add() expects localised amounts
     $contribParams['non_deductible_amount'] = trim(CRM_Utils_Money::format($contribParams['non_deductible_amount'], ' '));
     $contribParams['total_amount'] = trim(CRM_Utils_Money::format($contribParams['total_amount'], ' '));
     // Prepare soft contribution due to pcp or Submit Credit / Debit Card Contribution by admin.
     if (!empty($params['pcp_made_through_id']) || !empty($params['soft_credit_to'])) {
         // if its due to pcp
         if (!empty($params['pcp_made_through_id'])) {
             $contribSoftContactId = CRM_Core_DAO::getFieldValue('CRM_PCP_DAO_PCP', $params['pcp_made_through_id'], 'contact_id');
         } else {
             $contribSoftContactId = CRM_Utils_Array::value('soft_credit_to', $params);
         }
         // Pass these details onto with the contribution to make them
         // available at hook_post_process, CRM-8908
         $contribParams['soft_credit_to'] = $params['soft_credit_to'] = $contribSoftContactId;
     }
     if (isset($params['amount'])) {
         $contribParams['line_item'] = $form->_lineItem;
         //add contribution record
         $contribution = CRM_Contribute_BAO_Contribution::add($contribParams, $ids);
         if (is_a($contribution, 'CRM_Core_Error')) {
             $message = CRM_Core_Error::getMessages($contribution);
             CRM_Core_Error::fatal($message);
         }
         // lets store it in the form variable so postProcess hook can get to this and use it
         $form->_contributionID = $contribution->id;
     }
     //CRM-13981, processing honor contact into soft-credit contribution
     CRM_Contact_Form_ProfileContact::postProcess($form);
     // process soft credit / pcp pages
     CRM_Contribute_Form_Contribution_Confirm::processPcpSoft($params, $contribution);
     //handle pledge stuff.
     if (empty($form->_params['separate_membership_payment']) && !empty($form->_values['pledge_block_id']) && (!empty($form->_params['is_pledge']) || !empty($form->_values['pledge_id']))) {
         if (!empty($form->_values['pledge_id'])) {
             //when user doing pledge payments.
             //update the schedule when payment(s) are made
             foreach ($form->_params['pledge_amount'] as $paymentId => $dontCare) {
                 $scheduledAmount = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment', $paymentId, 'scheduled_amount', 'id');
                 $pledgePaymentParams = array('id' => $paymentId, 'contribution_id' => $contribution->id, 'status_id' => $contribution->contribution_status_id, 'actual_amount' => $scheduledAmount);
                 CRM_Pledge_BAO_PledgePayment::add($pledgePaymentParams);
             }
             //update pledge status according to the new payment statuses
             CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($form->_values['pledge_id']);
         } else {
             //when user creating pledge record.
             $pledgeParams = array();
             $pledgeParams['contact_id'] = $contribution->contact_id;
             $pledgeParams['installment_amount'] = $pledgeParams['actual_amount'] = $contribution->total_amount;
             $pledgeParams['contribution_id'] = $contribution->id;
             $pledgeParams['contribution_page_id'] = $contribution->contribution_page_id;
             $pledgeParams['financial_type_id'] = $contribution->financial_type_id;
             $pledgeParams['frequency_interval'] = $params['pledge_frequency_interval'];
             $pledgeParams['installments'] = $params['pledge_installments'];
             $pledgeParams['frequency_unit'] = $params['pledge_frequency_unit'];
             if ($pledgeParams['frequency_unit'] == 'month') {
                 $pledgeParams['frequency_day'] = intval(date("d"));
             } else {
                 $pledgeParams['frequency_day'] = 1;
             }
             $pledgeParams['create_date'] = $pledgeParams['start_date'] = $pledgeParams['scheduled_date'] = date("Ymd");
             $pledgeParams['status_id'] = $contribution->contribution_status_id;
             $pledgeParams['max_reminders'] = $form->_values['max_reminders'];
             $pledgeParams['initial_reminder_day'] = $form->_values['initial_reminder_day'];
             $pledgeParams['additional_reminder_day'] = $form->_values['additional_reminder_day'];
             $pledgeParams['is_test'] = $contribution->is_test;
             $pledgeParams['acknowledge_date'] = date('Ymd');
             $pledgeParams['original_installment_amount'] = $pledgeParams['installment_amount'];
             //inherit campaign from contirb page.
             $pledgeParams['campaign_id'] = $campaignId;
             $pledge = CRM_Pledge_BAO_Pledge::create($pledgeParams);
             $form->_params['pledge_id'] = $pledge->id;
             //send acknowledgment email. only when pledge is created
             if ($pledge->id) {
                 //build params to send acknowledgment.
                 $pledgeParams['id'] = $pledge->id;
                 $pledgeParams['receipt_from_name'] = $form->_values['receipt_from_name'];
                 $pledgeParams['receipt_from_email'] = $form->_values['receipt_from_email'];
                 //scheduled amount will be same as installment_amount.
                 $pledgeParams['scheduled_amount'] = $pledgeParams['installment_amount'];
                 //get total pledge amount.
                 $pledgeParams['total_pledge_amount'] = $pledge->amount;
                 CRM_Pledge_BAO_Pledge::sendAcknowledgment($form, $pledgeParams);
             }
         }
     }
     if ($online && $contribution) {
         CRM_Core_BAO_CustomValueTable::postProcess($form->_params, CRM_Core_DAO::$_nullArray, 'civicrm_contribution', $contribution->id, 'Contribution');
     } elseif ($contribution) {
         //handle custom data.
         $params['contribution_id'] = $contribution->id;
         if (!empty($params['custom']) && is_array($params['custom']) && !is_a($contribution, 'CRM_Core_Error')) {
             CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_contribution', $contribution->id);
         }
     }
     // Save note
     if ($contribution && !empty($params['contribution_note'])) {
         $noteParams = array('entity_table' => 'civicrm_contribution', 'note' => $params['contribution_note'], 'entity_id' => $contribution->id, 'contact_id' => $contribution->contact_id, 'modified_date' => date('Ymd'));
         CRM_Core_BAO_Note::add($noteParams, array());
     }
     if (isset($params['related_contact'])) {
         $contactID = $params['related_contact'];
     } elseif (isset($params['cms_contactID'])) {
         $contactID = $params['cms_contactID'];
     }
     //create contribution activity w/ individual and target
     //activity w/ organisation contact id when onbelf, CRM-4027
     $targetContactID = NULL;
     if (!empty($params['hidden_onbehalf_profile'])) {
         $targetContactID = $contribution->contact_id;
         $contribution->contact_id = $contactID;
     }
     // create an activity record
     if ($contribution) {
         CRM_Activity_BAO_Activity::addActivity($contribution, NULL, $targetContactID);
     }
     $transaction->commit();
     // CRM-13074 - create the CMSUser after the transaction is completed as it
     // is not appropriate to delete a valid contribution if a user create problem occurs
     CRM_Contribute_BAO_Contribution_Utils::createCMSUser($params, $contactID, 'email-' . $form->_bltID);
     return $contribution;
 }
Пример #18
0
 /**
  * function to create the event
  *
  * @param array $params reference array contains the values submitted by the form
  * 
  * @access public
  * @static 
  * 
  */
 public static function create(&$params)
 {
     require_once 'CRM/Core/Transaction.php';
     $transaction = new CRM_Core_Transaction();
     $event = self::add($params);
     if (is_a($event, 'CRM_Core_Error')) {
         CRM_Core_DAO::transaction('ROLLBACK');
         return $event;
     }
     $session =& CRM_Core_Session::singleton();
     $contactId = $session->get('userID');
     if (!$contactId) {
         $contactId = CRM_Utils_Array::value('contact_id', $params);
     }
     // Log the information on successful add/edit of Event
     require_once 'CRM/Core/BAO/Log.php';
     $logParams = array('entity_table' => 'civicrm_event', 'entity_id' => $event->id, 'modified_id' => $contactId, 'modified_date' => date('Ymd'));
     CRM_Core_BAO_Log::add($logParams);
     if (CRM_Utils_Array::value('custom', $params) && is_array($params['custom'])) {
         require_once 'CRM/Core/BAO/CustomValueTable.php';
         CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_event', $event->id);
     }
     $transaction->commit();
     return $event;
 }
Пример #19
0
 /**
  * Takes an associative array and creates a membership object.
  *
  * @param array $params
  *   (reference ) an assoc array of name/value pairs.
  * @param array $ids
  *   The array that holds all the db ids.
  * @param bool $skipRedirect
  * @param string $activityType
  *
  * @throws CRM_Core_Exception
  *
  * @return CRM_Member_BAO_Membership|CRM_Core_Error
  */
 public static function create(&$params, &$ids, $skipRedirect = FALSE, $activityType = 'Membership Signup')
 {
     // always calculate status if is_override/skipStatusCal is not true.
     // giving respect to is_override during import.  CRM-4012
     // To skip status calculation we should use 'skipStatusCal'.
     // eg pay later membership, membership update cron CRM-3984
     if (empty($params['is_override']) && empty($params['skipStatusCal'])) {
         $dates = array('start_date', 'end_date', 'join_date');
         // Declare these out of courtesy as IDEs don't pick up the setting of them below.
         $start_date = $end_date = $join_date = NULL;
         foreach ($dates as $date) {
             ${$date} = $params[$date] = CRM_Utils_Date::processDate(CRM_Utils_Array::value($date, $params), NULL, TRUE, 'Ymd');
         }
         //fix for CRM-3570, during import exclude the statuses those having is_admin = 1
         $excludeIsAdmin = CRM_Utils_Array::value('exclude_is_admin', $params, FALSE);
         //CRM-3724 always skip is_admin if is_override != true.
         if (!$excludeIsAdmin && empty($params['is_override'])) {
             $excludeIsAdmin = TRUE;
         }
         $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($start_date, $end_date, $join_date, 'today', $excludeIsAdmin, CRM_Utils_Array::value('membership_type_id', $params), $params);
         if (empty($calcStatus)) {
             // Redirect the form in case of error
             // @todo this redirect in the BAO layer is really bad & should be moved to the form layer
             // however since we have no idea how (if) this is triggered we can't safely move / remove it
             // NB I tried really hard to trigger this error from backoffice membership form in order to test it
             // and am convinced form validation is complete on that form WRT this error.
             $errorParams = array('message_title' => ts('No valid membership status for given dates.'), 'legacy_redirect_path' => 'civicrm/contact/view', 'legacy_redirect_query' => "reset=1&force=1&cid={$params['contact_id']}&selectedChild=member");
             throw new CRM_Core_Exception(ts("The membership cannot be saved because the status cannot be calculated for start_date: {$start_date} end_date {$end_date} join_date {$join_date} as at " . date('Y-m-d H:i:s')), 0, $errorParams);
         }
         $params['status_id'] = $calcStatus['id'];
     }
     // data cleanup only: all verifications on number of related memberships are done upstream in:
     // CRM_Member_BAO_Membership::createRelatedMemberships()
     // CRM_Contact_BAO_Relationship::relatedMemberships()
     if (isset($params['owner_membership_id'])) {
         unset($params['max_related']);
     } else {
         // if membership allows related, default max_related to value in membership_type
         if (!array_key_exists('max_related', $params) && !empty($params['membership_type_id'])) {
             $membershipType = CRM_Member_BAO_MembershipType::getMembershipTypeDetails($params['membership_type_id']);
             if (isset($membershipType['relationship_type_id'])) {
                 $params['max_related'] = CRM_Utils_Array::value('max_related', $membershipType);
             }
         }
     }
     $transaction = new CRM_Core_Transaction();
     $membership = self::add($params, $ids);
     if (is_a($membership, 'CRM_Core_Error')) {
         $transaction->rollback();
         return $membership;
     }
     // add custom field values
     if (!empty($params['custom']) && is_array($params['custom'])) {
         CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_membership', $membership->id);
     }
     $params['membership_id'] = $membership->id;
     if (isset($ids['membership'])) {
         $ids['contribution'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipPayment', $membership->id, 'contribution_id', 'membership_id');
     }
     $params['skipLineItem'] = TRUE;
     //record contribution for this membership
     if (!empty($params['contribution_status_id']) && empty($params['relate_contribution_id'])) {
         $memInfo = array_merge($params, array('membership_id' => $membership->id));
         $params['contribution'] = self::recordMembershipContribution($memInfo, $ids);
     }
     if (!empty($params['lineItems'])) {
         $params['line_item'] = $params['lineItems'];
     }
     //do cleanup line  items if membership edit the Membership type.
     if (empty($ids['contribution']) && !empty($ids['membership'])) {
         CRM_Price_BAO_LineItem::deleteLineItems($ids['membership'], 'civicrm_membership');
     }
     if (!empty($params['line_item']) && empty($ids['contribution'])) {
         CRM_Price_BAO_LineItem::processPriceSet($membership->id, $params['line_item'], CRM_Utils_Array::value('contribution', $params));
     }
     //insert payment record for this membership
     if (!empty($params['relate_contribution_id'])) {
         CRM_Member_BAO_MembershipPayment::create(array('membership_id' => $membership->id, 'membership_type_id' => $membership->membership_type_id, 'contribution_id' => $params['relate_contribution_id']));
     }
     // add activity record only during create mode and renew mode
     // also add activity if status changed CRM-3984 and CRM-2521
     if (empty($ids['membership']) || $activityType == 'Membership Renewal' || !empty($params['createActivity'])) {
         if (!empty($ids['membership'])) {
             $data = array();
             CRM_Core_DAO::commonRetrieveAll('CRM_Member_DAO_Membership', 'id', $membership->id, $data, array('contact_id', 'membership_type_id', 'source'));
             $membership->contact_id = $data[$membership->id]['contact_id'];
             $membership->membership_type_id = $data[$membership->id]['membership_type_id'];
             $membership->source = CRM_Utils_Array::value('source', $data[$membership->id]);
         }
         // since we are going to create activity record w/
         // individual contact as a target in case of on behalf signup,
         // so get the copy of organization id, CRM-5551
         $realMembershipContactId = $membership->contact_id;
         // create activity source = individual, target = org CRM-4027
         $targetContactID = NULL;
         if (!empty($params['is_for_organization'])) {
             $targetContactID = $membership->contact_id;
             $membership->contact_id = CRM_Utils_Array::value('userId', $ids);
         }
         if (empty($membership->contact_id) && !empty($membership->owner_membership_id)) {
             $membership->contact_id = $realMembershipContactId;
         }
         if (!empty($ids['membership']) && $activityType != 'Membership Signup') {
             CRM_Activity_BAO_Activity::addActivity($membership, $activityType, $targetContactID);
         } elseif (empty($ids['membership'])) {
             CRM_Activity_BAO_Activity::addActivity($membership, $activityType, $targetContactID);
         }
         // we might created activity record w/ individual
         // contact as target so update membership object w/
         // original organization id, CRM-5551
         $membership->contact_id = $realMembershipContactId;
     }
     $transaction->commit();
     self::createRelatedMemberships($params, $membership);
     // do not add to recent items for import, CRM-4399
     if (empty($params['skipRecentView'])) {
         $url = CRM_Utils_System::url('civicrm/contact/view/membership', "action=view&reset=1&id={$membership->id}&cid={$membership->contact_id}&context=home");
         if (empty($membership->membership_type_id)) {
             // ie in an update situation.
             $membership->find(TRUE);
         }
         $membershipTypes = CRM_Member_PseudoConstant::membershipType();
         $title = CRM_Contact_BAO_Contact::displayName($membership->contact_id) . ' - ' . ts('Membership Type:') . ' ' . $membershipTypes[$membership->membership_type_id];
         $recentOther = array();
         if (CRM_Core_Permission::checkActionPermission('CiviMember', CRM_Core_Action::UPDATE)) {
             $recentOther['editUrl'] = CRM_Utils_System::url('civicrm/contact/view/membership', "action=update&reset=1&id={$membership->id}&cid={$membership->contact_id}&context=home");
         }
         if (CRM_Core_Permission::checkActionPermission('CiviMember', CRM_Core_Action::DELETE)) {
             $recentOther['deleteUrl'] = CRM_Utils_System::url('civicrm/contact/view/membership', "action=delete&reset=1&id={$membership->id}&cid={$membership->contact_id}&context=home");
         }
         // add the recently created Membership
         CRM_Utils_Recent::add($title, $url, $membership->id, 'Membership', $membership->contact_id, NULL, $recentOther);
     }
     return $membership;
 }
Пример #20
0
 /**
  * this function checks whether the values of the custom fields in $params are
  * the same as the values of the custom fields of the relation with given
  * $relationshipId.
  *
  * @param array $params (reference) an assoc array of name/value pairs
  * @param int $relationshipId ID of an existing duplicate relation
  *
  * @return boolean true if custom field values are identical
  * @access private
  * @static
  */
 private static function checkDuplicateCustomFields(&$params, $relationshipId)
 {
     // Get the custom values of the existing relationship.
     $existingValues = CRM_Core_BAO_CustomValueTable::getEntityValues($relationshipId, 'Relationship');
     // Create a similar array for the new relationship.
     $newValues = array();
     if (array_key_exists('custom', $params)) {
         // $params['custom'] seems to be an array. Each value is again an array.
         // This array contains one value (key -1), and this value seems to be
         // an array with the information about the custom value.
         foreach ($params['custom'] as $value) {
             foreach ($value as $customValue) {
                 $newValues[$customValue['custom_field_id']] = $customValue['value'];
             }
         }
     }
     // Calculate difference between arrays. If the only key-value pairs
     // that are in one array but not in the other are empty, the
     // custom fields are considered to be equal.
     // See https://github.com/civicrm/civicrm-core/pull/6515#issuecomment-137985667
     $diff1 = array_diff_assoc($existingValues, $newValues);
     $diff2 = array_diff_assoc($newValues, $existingValues);
     return !array_filter($diff1) && !array_filter($diff2);
 }
Пример #21
0
 /**
  * Process the form after the input has been submitted and validated.
  *
  *
  * @return void
  */
 public function postProcess()
 {
     $params = $this->exportValues();
     $dates = array('join_date', 'membership_start_date', 'membership_end_date');
     if (isset($params['field'])) {
         $customFields = array();
         foreach ($params['field'] as $key => $value) {
             $ids['membership'] = $key;
             if (!empty($value['membership_source'])) {
                 $value['source'] = $value['membership_source'];
             }
             if (!empty($value['membership_type'])) {
                 $membershipTypeId = $value['membership_type_id'] = $value['membership_type'][1];
             }
             unset($value['membership_source']);
             unset($value['membership_type']);
             //Get the membership status
             $value['status_id'] = CRM_Utils_Array::value('membership_status', $value) ? $value['membership_status'] : CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $key, 'status_id');
             unset($value['membership_status']);
             foreach ($dates as $val) {
                 if (isset($value[$val])) {
                     $value[$val] = CRM_Utils_Date::processDate($value[$val]);
                 }
             }
             if (empty($customFields)) {
                 if (empty($value['membership_type_id'])) {
                     $membershipTypeId = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $key, 'membership_type_id');
                 }
                 // membership type custom data
                 $customFields = CRM_Core_BAO_CustomField::getFields('Membership', FALSE, FALSE, $membershipTypeId);
                 $customFields = CRM_Utils_Array::crmArrayMerge($customFields, CRM_Core_BAO_CustomField::getFields('Membership', FALSE, FALSE, NULL, NULL, TRUE));
             }
             //check for custom data
             $value['custom'] = CRM_Core_BAO_CustomField::postProcess($params['field'][$key], $key, 'Membership', $membershipTypeId);
             $membership = CRM_Member_BAO_Membership::add($value, $ids);
             // add custom field values
             if (!empty($value['custom']) && is_array($value['custom'])) {
                 CRM_Core_BAO_CustomValueTable::store($value['custom'], 'civicrm_membership', $membership->id);
             }
         }
         CRM_Core_Session::setStatus(ts("Your updates have been saved."), ts('Saved'), 'success');
     } else {
         CRM_Core_Session::setStatus(ts("No updates have been saved."), ts('Not Saved'), 'alert');
     }
 }
Пример #22
0
 /**
  * Takes an associative array and adds address.
  *
  * @param array $params
  *   (reference ) an assoc array of name/value pairs.
  * @param bool $fixAddress
  *   True if you need to fix (format) address values.
  *                               before inserting in db
  *
  * @return CRM_Core_BAO_Address|null
  */
 public static function add(&$params, $fixAddress)
 {
     static $customFields = NULL;
     $address = new CRM_Core_DAO_Address();
     // fixAddress mode to be done
     if ($fixAddress) {
         CRM_Core_BAO_Address::fixAddress($params);
     }
     $hook = empty($params['id']) ? 'create' : 'edit';
     CRM_Utils_Hook::pre($hook, 'Address', CRM_Utils_Array::value('id', $params), $params);
     // if id is set & is_primary isn't we can assume no change
     if (is_numeric(CRM_Utils_Array::value('is_primary', $params)) || empty($params['id'])) {
         CRM_Core_BAO_Block::handlePrimary($params, get_class());
     }
     $config = CRM_Core_Config::singleton();
     $address->copyValues($params);
     $address->save();
     if ($address->id) {
         if (!$customFields) {
             $customFields = CRM_Core_BAO_CustomField::getFields('Address', FALSE, TRUE);
         }
         if (!empty($customFields)) {
             $addressCustom = CRM_Core_BAO_CustomField::postProcess($params, $address->id, 'Address', TRUE);
         }
         if (!empty($addressCustom)) {
             CRM_Core_BAO_CustomValueTable::store($addressCustom, 'civicrm_address', $address->id);
         }
         //call the function to sync shared address
         self::processSharedAddress($address->id, $params);
         // call the function to create shared relationships
         // we only create create relationship if address is shared by Individual
         if (!CRM_Utils_System::isNull($address->master_id)) {
             self::processSharedAddressRelationship($address->master_id, $params);
         }
         // lets call the post hook only after we've done all the follow on processing
         CRM_Utils_Hook::post($hook, 'Address', $address->id, $address);
     }
     return $address;
 }
Пример #23
0
 /**
  * process the form after the input has been submitted and validated
  *
  * @access public
  *
  * @return void
  */
 public function postProcess()
 {
     $params = $this->exportValues();
     if (isset($params['field'])) {
         foreach ($params['field'] as $key => $value) {
             $value['custom'] = CRM_Core_BAO_CustomField::postProcess($value, CRM_Core_DAO::$_nullObject, $key, 'Activity');
             $value['id'] = $key;
             if ($value['activity_date_time']) {
                 $value['activity_date_time'] = CRM_Utils_Date::processDate($value['activity_date_time'], $value['activity_date_time_time']);
             }
             if (!empty($value['activity_status_id'])) {
                 $value['status_id'] = $value['activity_status_id'];
             }
             if (!empty($value['activity_details'])) {
                 $value['details'] = $value['activity_details'];
             }
             if (!empty($value['activity_duration'])) {
                 $value['duration'] = $value['activity_duration'];
             }
             if (!empty($value['activity_location'])) {
                 $value['location'] = $value['activity_location'];
             }
             if (!empty($value['activity_subject'])) {
                 $value['subject'] = $value['activity_subject'];
             }
             $query = "\nSELECT a.activity_type_id, ac.contact_id\nFROM   civicrm_activity a\nJOIN   civicrm_activity_contact ac ON ( ac.activity_id = a.id\nAND    ac.record_type_id = %2 )\nWHERE  a.id = %1 ";
             $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
             $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
             $params = array(1 => array($key, 'Integer'), 2 => array($sourceID, 'Integer'));
             $dao = CRM_Core_DAO::executeQuery($query, $params);
             $dao->fetch();
             // Get Activity Type ID
             $value['activity_type_id'] = $dao->activity_type_id;
             // Get Conatct ID
             $value['source_contact_id'] = $dao->contact_id;
             // make call use API 3
             $value['version'] = 3;
             $activityId = civicrm_api('activity', 'update', $value);
             // add custom field values
             if (!empty($value['custom']) && is_array($value['custom'])) {
                 CRM_Core_BAO_CustomValueTable::store($value['custom'], 'civicrm_activity', $activityId['id']);
             }
         }
         CRM_Core_Session::setStatus("", ts("Updates Saved"), "success");
     } else {
         CRM_Core_Session::setStatus("", ts("No Updates Saved"), "info");
     }
 }
Пример #24
0
 /**
  * Takes an associative array and creates a contribution object.
  *
  * the function extract all the params it needs to initialize the create a
  * contribution object. the params array could contain additional unused name/value
  * pairs
  *
  * @param array $params
  *   (reference ) an assoc array of name/value pairs.
  *
  * @return CRM_Contribute_BAO_Contribution
  * @todo move hook calls / extended logic to create - requires changing calls to call create not add
  */
 public static function add(&$params)
 {
     if (!empty($params['id'])) {
         CRM_Utils_Hook::pre('edit', 'ContributionRecur', $params['id'], $params);
     } else {
         CRM_Utils_Hook::pre('create', 'ContributionRecur', NULL, $params);
     }
     // make sure we're not creating a new recurring contribution with the same transaction ID
     // or invoice ID as an existing recurring contribution
     $duplicates = array();
     if (self::checkDuplicate($params, $duplicates)) {
         $error = CRM_Core_Error::singleton();
         $d = implode(', ', $duplicates);
         $error->push(CRM_Core_Error::DUPLICATE_CONTRIBUTION, 'Fatal', array($d), "Found matching recurring contribution(s): {$d}");
         return $error;
     }
     $recurring = new CRM_Contribute_BAO_ContributionRecur();
     $recurring->copyValues($params);
     $recurring->id = CRM_Utils_Array::value('id', $params);
     // set currency for CRM-1496
     if (empty($params['id']) && !isset($recurring->currency)) {
         $config = CRM_Core_Config::singleton();
         $recurring->currency = $config->defaultCurrency;
     }
     $result = $recurring->save();
     if (!empty($params['id'])) {
         CRM_Utils_Hook::post('edit', 'ContributionRecur', $recurring->id, $recurring);
     } else {
         CRM_Utils_Hook::post('create', 'ContributionRecur', $recurring->id, $recurring);
     }
     if (!empty($params['custom']) && is_array($params['custom'])) {
         CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_contribution_recur', $recurring->id);
     }
     return $result;
 }
Пример #25
0
 /**
  * takes an associative array and creates a case object
  *
  * @param array $params (reference ) an assoc array of name/value pairs
  *
  * @internal param array $ids the array that holds all the db ids
  *
  * @return object CRM_Case_BAO_Case object
  * @access public
  * @static
  */
 static function &create(&$params)
 {
     $transaction = new CRM_Core_Transaction();
     if (!empty($params['id'])) {
         CRM_Utils_Hook::pre('edit', 'Case', $params['id'], $params);
     } else {
         CRM_Utils_Hook::pre('create', 'Case', NULL, $params);
     }
     $case = self::add($params);
     if (!empty($params['custom']) && is_array($params['custom'])) {
         CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_case', $case->id);
     }
     if (is_a($case, 'CRM_Core_Error')) {
         $transaction->rollback();
         return $case;
     }
     if (!empty($params['id'])) {
         CRM_Utils_Hook::post('edit', 'Case', $case->id, $case);
     } else {
         CRM_Utils_Hook::post('create', 'Case', $case->id, $case);
     }
     $transaction->commit();
     //we are not creating log for case
     //since case log can be tracked using log for activity.
     return $case;
 }
Пример #26
0
 /**
  * function to create the event
  *
  * @param array $params reference array contains the values submitted by the form
  *
  * @return object
  * @access public
  * @static
  *
  */
 public static function create(&$params)
 {
     $transaction = new CRM_Core_Transaction();
     if (empty($params['is_template'])) {
         $params['is_template'] = 0;
     }
     // check if new event, if so set the created_id (if not set)
     // and always set created_date to now
     if (empty($params['id'])) {
         if (empty($params['created_id'])) {
             $session = CRM_Core_Session::singleton();
             $params['created_id'] = $session->get('userID');
         }
         $params['created_date'] = date('YmdHis');
     }
     $event = self::add($params);
     CRM_Price_BAO_PriceSet::setPriceSets($params, $event, 'event');
     if (is_a($event, 'CRM_Core_Error')) {
         CRM_Core_DAO::transaction('ROLLBACK');
         return $event;
     }
     $session = CRM_Core_Session::singleton();
     $contactId = $session->get('userID');
     if (!$contactId) {
         $contactId = CRM_Utils_Array::value('contact_id', $params);
     }
     // Log the information on successful add/edit of Event
     $logParams = array('entity_table' => 'civicrm_event', 'entity_id' => $event->id, 'modified_id' => $contactId, 'modified_date' => date('Ymd'));
     CRM_Core_BAO_Log::add($logParams);
     if (!empty($params['custom']) && is_array($params['custom'])) {
         CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_event', $event->id);
     }
     $transaction->commit();
     return $event;
 }
Пример #27
0
 /**
  * Process the Memberships.
  *
  * @param array $membershipParams
  *   Array of membership fields.
  * @param int $contactID
  *   Contact id.
  * @param CRM_Contribute_Form_Contribution_Confirm $form
  *   Confirmation form object.
  *
  * @param array $premiumParams
  * @param null $customFieldsFormatted
  * @param null $includeFieldTypes
  *
  * @param array $membershipDetails
  *
  * @param array $membershipTypeIDs
  *
  * @param bool $isPaidMembership
  * @param array $membershipID
  *
  * @param bool $isProcessSeparateMembershipTransaction
  *
  * @param int $financialTypeID
  * @param array $membershipLineItems
  *   Line items specific to membership payment that is separate to contribution.
  * @param bool $isPayLater
  * @param bool $isPending
  *
  * @throws \CRM_Core_Exception
  */
 protected function postProcessMembership($membershipParams, $contactID, &$form, $premiumParams, $customFieldsFormatted = NULL, $includeFieldTypes = NULL, $membershipDetails, $membershipTypeIDs, $isPaidMembership, $membershipID, $isProcessSeparateMembershipTransaction, $financialTypeID, $membershipLineItems, $isPayLater, $isPending)
 {
     $membershipContribution = NULL;
     $isTest = CRM_Utils_Array::value('is_test', $membershipParams, FALSE);
     $errors = $createdMemberships = $paymentResults = array();
     $form->_values['isMembership'] = TRUE;
     $isRecurForFirstTransaction = CRM_Utils_Array::value('is_recur', $form->_values, CRM_Utils_Array::value('is_recur', $membershipParams));
     $totalAmount = $membershipParams['amount'];
     if ($isPaidMembership) {
         if ($isProcessSeparateMembershipTransaction) {
             // If we have 2 transactions only one can use the invoice id.
             $membershipParams['invoiceID'] .= '-2';
             if (!empty($membershipParams['auto_renew'])) {
                 $isRecurForFirstTransaction = FALSE;
             }
         }
         $paymentResult = CRM_Contribute_BAO_Contribution_Utils::processConfirm($form, $membershipParams, $contactID, $financialTypeID, 'membership', $isTest, $isRecurForFirstTransaction);
         if (!empty($paymentResult['contribution'])) {
             $this->postProcessPremium($premiumParams, $paymentResult['contribution']);
             //note that this will be over-written if we are using a separate membership transaction. Otherwise there is only one
             $membershipContribution = $paymentResult['contribution'];
             // Save the contribution ID so that I can be used in email receipts
             // For example, if you need to generate a tax receipt for the donation only.
             $form->_values['contribution_other_id'] = $membershipContribution->id;
         }
     }
     if ($isProcessSeparateMembershipTransaction) {
         try {
             $form->_lineItem = $membershipLineItems;
             if (empty($form->_params['auto_renew']) && !empty($membershipParams['is_recur'])) {
                 unset($membershipParams['is_recur']);
             }
             list($membershipContribution, $secondPaymentResult) = $this->processSecondaryFinancialTransaction($contactID, $form, $membershipParams, $isTest, $membershipLineItems, CRM_Utils_Array::value('minimum_fee', $membershipDetails, 0), CRM_Utils_Array::value('financial_type_id', $membershipDetails));
             $paymentResults[] = array('contribution_id' => $membershipContribution->id, 'result' => $secondPaymentResult);
         } catch (CRM_Core_Exception $e) {
             $errors[2] = $e->getMessage();
             $membershipContribution = NULL;
         }
     }
     $membership = NULL;
     if (!empty($membershipContribution) && !is_a($membershipContribution, 'CRM_Core_Error')) {
         $membershipContributionID = $membershipContribution->id;
     }
     //@todo - why is this nested so deep? it seems like it could be just set on the calling function on the form layer
     if (isset($membershipParams['onbehalf']) && !empty($membershipParams['onbehalf']['member_campaign_id'])) {
         $form->_params['campaign_id'] = $membershipParams['onbehalf']['member_campaign_id'];
     }
     //@todo it should no longer be possible for it to get to this point & membership to not be an array
     if (is_array($membershipTypeIDs) && !empty($membershipContributionID)) {
         $typesTerms = CRM_Utils_Array::value('types_terms', $membershipParams, array());
         foreach ($membershipTypeIDs as $memType) {
             $numTerms = CRM_Utils_Array::value($memType, $typesTerms, 1);
             if (!empty($membershipContribution)) {
                 $pendingStatus = CRM_Core_OptionGroup::getValue('contribution_status', 'Pending', 'name');
                 $pending = $membershipContribution->contribution_status_id == $pendingStatus ? TRUE : FALSE;
             } else {
                 $pending = $isPending;
             }
             $contributionRecurID = isset($form->_params['contributionRecurID']) ? $form->_params['contributionRecurID'] : NULL;
             $membershipSource = NULL;
             if (!empty($form->_params['membership_source'])) {
                 $membershipSource = $form->_params['membership_source'];
             } elseif (isset($form->_values['title']) && !empty($form->_values['title'])) {
                 $membershipSource = ts('Online Contribution:') . ' ' . $form->_values['title'];
             }
             $isPayLater = NULL;
             if (isset($form->_params)) {
                 $isPayLater = CRM_Utils_Array::value('is_pay_later', $form->_params);
             }
             $campaignId = NULL;
             if (isset($form->_values) && is_array($form->_values) && !empty($form->_values)) {
                 $campaignId = CRM_Utils_Array::value('campaign_id', $form->_params);
                 if (!array_key_exists('campaign_id', $form->_params)) {
                     $campaignId = CRM_Utils_Array::value('campaign_id', $form->_values);
                 }
             }
             list($membership, $renewalMode, $dates) = CRM_Member_BAO_Membership::renewMembership($contactID, $memType, $isTest, date('YmdHis'), CRM_Utils_Array::value('cms_contactID', $membershipParams), $customFieldsFormatted, $numTerms, $membershipID, $pending, $contributionRecurID, $membershipSource, $isPayLater, $campaignId);
             $form->set('renewal_mode', $renewalMode);
             if (!empty($dates)) {
                 $form->assign('mem_start_date', CRM_Utils_Date::customFormat($dates['start_date'], '%Y%m%d'));
                 $form->assign('mem_end_date', CRM_Utils_Date::customFormat($dates['end_date'], '%Y%m%d'));
             }
             if (!empty($membershipContribution)) {
                 // update recurring id for membership record
                 CRM_Member_BAO_Membership::updateRecurMembership($membership, $membershipContribution);
                 CRM_Member_BAO_Membership::linkMembershipPayment($membership, $membershipContribution);
             }
         }
         if ($form->_priceSetId && !empty($form->_useForMember) && !empty($form->_lineItem)) {
             foreach ($form->_lineItem[$form->_priceSetId] as &$priceFieldOp) {
                 if (!empty($priceFieldOp['membership_type_id']) && isset($createdMemberships[$priceFieldOp['membership_type_id']])) {
                     $membershipOb = $createdMemberships[$priceFieldOp['membership_type_id']];
                     $priceFieldOp['start_date'] = $membershipOb->start_date ? CRM_Utils_Date::customFormat($membershipOb->start_date, '%B %E%f, %Y') : '-';
                     $priceFieldOp['end_date'] = $membershipOb->end_date ? CRM_Utils_Date::customFormat($membershipOb->end_date, '%B %E%f, %Y') : '-';
                 } else {
                     $priceFieldOp['start_date'] = $priceFieldOp['end_date'] = 'N/A';
                 }
             }
             $form->_values['lineItem'] = $form->_lineItem;
             $form->assign('lineItem', $form->_lineItem);
         }
     }
     if (!empty($errors)) {
         $message = $this->compileErrorMessage($errors);
         throw new CRM_Core_Exception($message);
     }
     $form->_params['createdMembershipIDs'] = array();
     // CRM-7851 - Moved after processing Payment Errors
     //@todo - the reasoning for this being here seems a little outdated
     foreach ($createdMemberships as $createdMembership) {
         CRM_Core_BAO_CustomValueTable::postProcess($form->_params, 'civicrm_membership', $createdMembership->id, 'Membership');
         $form->_params['createdMembershipIDs'][] = $createdMembership->id;
     }
     if (count($createdMemberships) == 1) {
         //presumably this is only relevant for exactly 1 membership
         $form->_params['membershipID'] = $createdMembership->id;
     }
     //CRM-15232: Check if membership is created and on the basis of it use
     //membership receipt template to send payment receipt
     if (count($createdMemberships)) {
         $form->_values['isMembership'] = TRUE;
     }
     if (isset($membershipContributionID)) {
         $form->_values['contribution_id'] = $membershipContributionID;
     }
     if ($form->_paymentProcessor) {
         // the is_monetary concept probably should be deprecated as it can be calculated from
         // the existence of 'amount' & seems fragile.
         if ($form->_values['is_monetary'] && $form->_amount > 0.0 && !$form->_params['is_pay_later']) {
             // call postProcess hook before leaving
             $form->postProcessHook();
         }
         $payment = Civi\Payment\System::singleton()->getByProcessor($form->_paymentProcessor);
         // The contribution_other_id is effectively the ID for the only contribution or the non-membership contribution.
         // Since we have called the membership contribution (in a 2 contribution scenario) this is out
         // primary-contribution compared to that - but let's face it - it's all just too hard & confusing at the moment!
         $paymentParams = array_merge($form->_params, array('contributionID' => $form->_values['contribution_other_id']));
         $paymentActionResult = $payment->doPayment($paymentParams, 'contribute');
         $paymentResults[] = array('contribution_id' => $paymentResult['contribution']->id, 'result' => $paymentActionResult);
         // Do not send an email if Recurring transaction is done via Direct Mode
         // Email will we sent when the IPN is received.
         foreach ($paymentResults as $result) {
             $this->completeTransaction($result['result'], $result['contribution_id']);
         }
         return;
     }
     $emailValues = $form->_values;
     // Finally send an email receipt for pay-later scenario (although it might sometimes be caught above!)
     if ($totalAmount == 0) {
         // This feels like a bizarre hack as the variable name doesn't seem to be directly connected to it's use in the template.
         $emailValues['useForMember'] = 0;
         $emailValues['membership_assign'] = 1;
         $emailValues['amount'] = 0;
     }
     CRM_Contribute_BAO_ContributionPage::sendMail($contactID, $emailValues, $isTest, FALSE, $includeFieldTypes);
 }
Пример #28
0
 /**
  * takes an associative array and creates a pledge object
  *
  * @param array $params (reference ) an assoc array of name/value pairs
  *
  * @return object CRM_Pledge_BAO_Pledge object
  * @access public
  * @static
  */
 static function &create(&$params)
 {
     //FIXME: a cludgy hack to fix the dates to MySQL format
     $dateFields = array('start_date', 'create_date', 'acknowledge_date', 'modified_date', 'cancel_date', 'end_date');
     foreach ($dateFields as $df) {
         if (isset($params[$df])) {
             $params[$df] = CRM_Utils_Date::isoToMysql($params[$df]);
         }
     }
     $transaction = new CRM_Core_Transaction();
     $paymentParams = array();
     $paymentParams['status_id'] = CRM_Utils_Array::value('status_id', $params);
     if (CRM_Utils_Array::value('installment_amount', $params)) {
         $params['amount'] = $params['installment_amount'] * $params['installments'];
     }
     //get All Payments status types.
     $paymentStatusTypes = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
     //update the pledge status only if it does NOT come from form
     if (!isset($params['pledge_status_id'])) {
         if (isset($params['contribution_id'])) {
             if ($params['installments'] > 1) {
                 $params['status_id'] = array_search('In Progress', $paymentStatusTypes);
             }
         } else {
             if (!empty($params['id'])) {
                 $params['status_id'] = CRM_Pledge_BAO_PledgePayment::calculatePledgeStatus($params['id']);
             } else {
                 $params['status_id'] = array_search('Pending', $paymentStatusTypes);
             }
         }
     }
     $pledge = self::add($params);
     if (is_a($pledge, 'CRM_Core_Error')) {
         $pledge->rollback();
         return $pledge;
     }
     //handle custom data.
     if (CRM_Utils_Array::value('custom', $params) && is_array($params['custom'])) {
         CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_pledge', $pledge->id);
     }
     // skip payment stuff inedit mode
     if (!isset($params['id']) || CRM_Utils_Array::value('is_pledge_pending', $params)) {
         //if pledge is pending delete all payments and recreate.
         if (CRM_Utils_Array::value('is_pledge_pending', $params)) {
             CRM_Pledge_BAO_PledgePayment::deletePayments($pledge->id);
         }
         //building payment params
         $paymentParams['pledge_id'] = $pledge->id;
         $paymentKeys = array('amount', 'installments', 'scheduled_date', 'frequency_unit', 'currency', 'frequency_day', 'frequency_interval', 'contribution_id', 'installment_amount', 'actual_amount');
         foreach ($paymentKeys as $key) {
             $paymentParams[$key] = CRM_Utils_Array::value($key, $params, NULL);
         }
         CRM_Pledge_BAO_PledgePayment::create($paymentParams);
     }
     $transaction->commit();
     $url = CRM_Utils_System::url('civicrm/contact/view/pledge', "action=view&reset=1&id={$pledge->id}&cid={$pledge->contact_id}&context=home");
     $recentOther = array();
     if (CRM_Core_Permission::checkActionPermission('CiviPledge', CRM_Core_Action::UPDATE)) {
         $recentOther['editUrl'] = CRM_Utils_System::url('civicrm/contact/view/pledge', "action=update&reset=1&id={$pledge->id}&cid={$pledge->contact_id}&context=home");
     }
     if (CRM_Core_Permission::checkActionPermission('CiviPledge', CRM_Core_Action::DELETE)) {
         $recentOther['deleteUrl'] = CRM_Utils_System::url('civicrm/contact/view/pledge', "action=delete&reset=1&id={$pledge->id}&cid={$pledge->contact_id}&context=home");
     }
     $contributionTypes = CRM_Contribute_PseudoConstant::financialType();
     $title = CRM_Contact_BAO_Contact::displayName($pledge->contact_id) . ' - (' . ts('Pledged') . ' ' . CRM_Utils_Money::format($pledge->amount, $pledge->currency) . ' - ' . CRM_Utils_Array::value($pledge->financial_type_id, $contributionTypes) . ')';
     // add the recently created Pledge
     CRM_Utils_Recent::add($title, $url, $pledge->id, 'Pledge', $pledge->contact_id, NULL, $recentOther);
     return $pledge;
 }
Пример #29
0
 /**
  * Handle process after the confirmation of payment by User.
  *
  * @param int $contactID
  * @param null $contribution
  * @param null $payment
  */
 public function confirmPostProcess($contactID = NULL, $contribution = NULL, $payment = NULL)
 {
     // add/update contact information
     $fields = array();
     unset($this->_params['note']);
     //to avoid conflict overwrite $this->_params
     $this->_params = $this->get('value');
     //get the amount of primary participant
     if (!empty($this->_params['is_primary'])) {
         $this->_params['fee_amount'] = $this->get('primaryParticipantAmount');
     }
     // add participant record
     $participant = CRM_Event_Form_Registration::addParticipant($this, $contactID);
     $this->_participantIDS[] = $participant->id;
     //setting register_by_id field and primaryContactId
     if (!empty($this->_params['is_primary'])) {
         $this->set('registerByID', $participant->id);
         $this->set('primaryContactId', $contactID);
         // CRM-10032
         $this->processFirstParticipant($participant->id);
     }
     CRM_Core_BAO_CustomValueTable::postProcess($this->_params, 'civicrm_participant', $participant->id, 'Participant');
     $createPayment = CRM_Utils_Array::value('amount', $this->_params, 0) != 0 ? TRUE : FALSE;
     // force to create zero amount payment, CRM-5095
     // we know the amout is zero since createPayment is false
     if (!$createPayment && (isset($contribution) && $contribution->id) && $this->_priceSetId && $this->_lineItem) {
         $createPayment = TRUE;
     }
     if ($createPayment && $this->_values['event']['is_monetary'] && !empty($this->_params['contributionID'])) {
         $paymentParams = array('participant_id' => $participant->id, 'contribution_id' => $contribution->id);
         $ids = array();
         $paymentPartcipant = CRM_Event_BAO_ParticipantPayment::create($paymentParams, $ids);
     }
     //set only primary participant's params for transfer checkout.
     // The concept of contributeMode is deprecated.
     if (($this->_contributeMode == 'checkout' || $this->_contributeMode == 'notify') && !empty($this->_params['is_primary'])) {
         $this->_params['participantID'] = $participant->id;
         $this->set('primaryParticipant', $this->_params);
     }
     $this->assign('action', $this->_action);
     // create CMS user
     if (!empty($this->_params['cms_create_account'])) {
         $this->_params['contactID'] = $contactID;
         if (array_key_exists('email-5', $this->_params)) {
             $mail = 'email-5';
         } else {
             foreach ($this->_params as $name => $dontCare) {
                 if (substr($name, 0, 5) == 'email') {
                     $mail = $name;
                     break;
                 }
             }
         }
         // we should use primary email for
         // 1. free event registration.
         // 2. pay later participant.
         // 3. waiting list participant.
         // 4. require approval participant.
         if (!empty($this->_params['is_pay_later']) || $this->_allowWaitlist || $this->_requireApproval || empty($this->_values['event']['is_monetary'])) {
             $mail = 'email-Primary';
         }
         if (!CRM_Core_BAO_CMSUser::create($this->_params, $mail)) {
             CRM_Core_Error::statusBounce(ts('Your profile is not saved and Account is not created.'));
         }
     }
 }
Пример #30
0
 /**
  * Takes an associative array and creates a contribution object.
  *
  * @param array $params
  *   (reference ) an assoc array of name/value pairs.
  * @param array $ids
  *   The array that holds all the db ids.
  *
  * @return CRM_Contribute_BAO_Contribution
  */
 public static function create(&$params, $ids = array())
 {
     $dateFields = array('receive_date', 'cancel_date', 'receipt_date', 'thankyou_date');
     foreach ($dateFields as $df) {
         if (isset($params[$df])) {
             $params[$df] = CRM_Utils_Date::isoToMysql($params[$df]);
         }
     }
     $transaction = new CRM_Core_Transaction();
     $contribution = self::add($params, $ids);
     if (is_a($contribution, 'CRM_Core_Error')) {
         $transaction->rollback();
         return $contribution;
     }
     $params['contribution_id'] = $contribution->id;
     if (!empty($params['custom']) && is_array($params['custom'])) {
         CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_contribution', $contribution->id);
     }
     $session = CRM_Core_Session::singleton();
     if (!empty($params['note'])) {
         $noteParams = array('entity_table' => 'civicrm_contribution', 'note' => $params['note'], 'entity_id' => $contribution->id, 'contact_id' => $session->get('userID'), 'modified_date' => date('Ymd'));
         if (!$noteParams['contact_id']) {
             $noteParams['contact_id'] = $params['contact_id'];
         }
         CRM_Core_BAO_Note::add($noteParams);
     }
     // make entry in batch entity batch table
     if (!empty($params['batch_id'])) {
         // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
         $titleFields = array('contact_id', 'total_amount', 'currency', 'financial_type_id');
         $retrieveRequired = 0;
         foreach ($titleFields as $titleField) {
             if (!isset($contribution->{$titleField})) {
                 $retrieveRequired = 1;
                 break;
             }
         }
         if ($retrieveRequired == 1) {
             $contribution->find(TRUE);
         }
     }
     // Handle soft credit and / or link to personal campaign page
     $softIDs = CRM_Contribute_BAO_ContributionSoft::getSoftCreditIds($contribution->id);
     $pcpId = CRM_Contribute_BAO_ContributionSoft::getSoftCreditIds($contribution->id, TRUE);
     if ($pcp = CRM_Utils_Array::value('pcp', $params)) {
         $softParams = array();
         $softParams['id'] = $pcpId ? $pcpId : NULL;
         $softParams['contribution_id'] = $contribution->id;
         $softParams['pcp_id'] = $pcp['pcp_made_through_id'];
         $softParams['contact_id'] = CRM_Core_DAO::getFieldValue('CRM_PCP_DAO_PCP', $pcp['pcp_made_through_id'], 'contact_id');
         $softParams['currency'] = $contribution->currency;
         $softParams['amount'] = $contribution->total_amount;
         $softParams['pcp_display_in_roll'] = CRM_Utils_Array::value('pcp_display_in_roll', $pcp);
         $softParams['pcp_roll_nickname'] = CRM_Utils_Array::value('pcp_roll_nickname', $pcp);
         $softParams['pcp_personal_note'] = CRM_Utils_Array::value('pcp_personal_note', $pcp);
         $softParams['soft_credit_type_id'] = CRM_Core_OptionGroup::getValue('soft_credit_type', 'pcp', 'name');
         $contributionSoft = CRM_Contribute_BAO_ContributionSoft::add($softParams);
         //Send notification to owner for PCP
         if ($contributionSoft->pcp_id && empty($pcpId)) {
             CRM_Contribute_Form_Contribution_Confirm::pcpNotifyOwner($contribution, $contributionSoft);
         }
     } elseif (array_key_exists('pcp', $params) && $pcpId) {
         $deleteParams = array('id' => $pcpId);
         CRM_Contribute_BAO_ContributionSoft::del($deleteParams);
     }
     if (isset($params['soft_credit'])) {
         $softParams = $params['soft_credit'];
         foreach ($softParams as $softParam) {
             if (!empty($softIDs)) {
                 $key = key($softIDs);
                 $softParam['id'] = $softIDs[$key];
                 unset($softIDs[$key]);
             }
             $softParam['contribution_id'] = $contribution->id;
             $softParam['currency'] = $contribution->currency;
             //case during Contribution Import when we assign soft contribution amount as contribution's total_amount by default
             if (empty($softParam['amount'])) {
                 $softParam['amount'] = $contribution->total_amount;
             }
             CRM_Contribute_BAO_ContributionSoft::add($softParam);
         }
         if (!empty($softIDs)) {
             foreach ($softIDs as $softID) {
                 if (!in_array($softID, $params['soft_credit_ids'])) {
                     $deleteParams = array('id' => $softID);
                     CRM_Contribute_BAO_ContributionSoft::del($deleteParams);
                 }
             }
         }
     }
     $transaction->commit();
     // check if activity record exist for this contribution, if
     // not add activity
     $activity = new CRM_Activity_DAO_Activity();
     $activity->source_record_id = $contribution->id;
     $activity->activity_type_id = CRM_Core_OptionGroup::getValue('activity_type', 'Contribution', 'name');
     if (!$activity->find(TRUE)) {
         if (empty($contribution->contact_id)) {
             $contribution->find(TRUE);
         }
         CRM_Activity_BAO_Activity::addActivity($contribution, 'Offline');
     } else {
         // CRM-13237 : if activity record found, update it with campaign id of contribution
         CRM_Core_DAO::setFieldValue('CRM_Activity_BAO_Activity', $activity->id, 'campaign_id', $contribution->campaign_id);
     }
     // do not add to recent items for import, CRM-4399
     if (empty($params['skipRecentView'])) {
         $url = CRM_Utils_System::url('civicrm/contact/view/contribution', "action=view&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home");
         // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
         $titleFields = array('contact_id', 'total_amount', 'currency', 'financial_type_id');
         $retrieveRequired = 0;
         foreach ($titleFields as $titleField) {
             if (!isset($contribution->{$titleField})) {
                 $retrieveRequired = 1;
                 break;
             }
         }
         if ($retrieveRequired == 1) {
             $contribution->find(TRUE);
         }
         $contributionTypes = CRM_Contribute_PseudoConstant::financialType();
         $title = CRM_Contact_BAO_Contact::displayName($contribution->contact_id) . ' - (' . CRM_Utils_Money::format($contribution->total_amount, $contribution->currency) . ' ' . ' - ' . $contributionTypes[$contribution->financial_type_id] . ')';
         $recentOther = array();
         if (CRM_Core_Permission::checkActionPermission('CiviContribute', CRM_Core_Action::UPDATE)) {
             $recentOther['editUrl'] = CRM_Utils_System::url('civicrm/contact/view/contribution', "action=update&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home");
         }
         if (CRM_Core_Permission::checkActionPermission('CiviContribute', CRM_Core_Action::DELETE)) {
             $recentOther['deleteUrl'] = CRM_Utils_System::url('civicrm/contact/view/contribution', "action=delete&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home");
         }
         // add the recently created Contribution
         CRM_Utils_Recent::add($title, $url, $contribution->id, 'Contribution', $contribution->contact_id, NULL, $recentOther);
     }
     return $contribution;
 }