Esempio n. 1
0
/**
 * create/update grant
 *
 * This API is used to create new grant or update any of the existing
 * In case of updating existing grant, id of that particular grant must
 * be in $params array.
 *
 * @param array $params  Associative array of property
 *                       name/value pairs to insert in new 'grant'
 *
 * @return array   grant array
 * {@getfields grant_create}
 * @access public
 */
function civicrm_api3_grant_create($params)
{
    $values = array();
    _civicrm_api3_custom_format_params($params, $values, 'Grant');
    $params = array_merge($values, $params);
    return _civicrm_api3_basic_create(_civicrm_api3_get_BAO(__FUNCTION__), $params, 'grant');
}
/**
 * Add or update a Contribution.
 *
 * @param array $params
 *   Input parameters.
 *
 * @throws API_Exception
 * @return array
 *   Api result array
 */
function civicrm_api3_contribution_create(&$params)
{
    $values = array();
    _civicrm_api3_custom_format_params($params, $values, 'Contribution');
    $params = array_merge($params, $values);
    if (!empty($params['id']) && !empty($params['contribution_status_id'])) {
        $error = array();
        //throw error for invalid status change such as setting completed back to pending
        //@todo this sort of validation belongs in the BAO not the API - if it is not an OK
        // action it needs to be blocked there. If it is Ok through a form it needs to be OK through the api
        CRM_Contribute_BAO_Contribution::checkStatusValidation(NULL, $params, $error);
        if (array_key_exists('contribution_status_id', $error)) {
            throw new API_Exception($error['contribution_status_id']);
        }
    }
    if (!empty($params['id']) && !empty($params['financial_type_id'])) {
        $error = array();
        CRM_Contribute_BAO_Contribution::checkFinancialTypeChange($params['financial_type_id'], $params['id'], $error);
        if (array_key_exists('financial_type_id', $error)) {
            throw new API_Exception($error['financial_type_id']);
        }
    }
    _civicrm_api3_contribution_create_legacy_support_45($params);
    // Make sure tax calculation is handled via api.
    $params = CRM_Contribute_BAO_Contribution::checkTaxAmount($params);
    return _civicrm_api3_basic_create(_civicrm_api3_get_BAO(__FUNCTION__), $params, 'Contribution');
}
Esempio n. 3
0
/**
 * Creates or updates an Activity. See the example for usage
 *
 * @param array  $params       Associative array of property name/value
 *                             pairs for the activity.
 * {@getfields pledge_create}
 *
 * @return array Array containing 'is_error' to denote success or failure and details of the created pledge
 *
 * @example PledgeCreate.php Standard create example
 *
 */
function civicrm_api3_pledge_create($params)
{
    _civicrm_api3_pledge_format_params($params, TRUE);
    $values = $params;
    //format the custom fields
    _civicrm_api3_custom_format_params($params, $values, 'Pledge');
    return _civicrm_api3_basic_create(_civicrm_api3_get_BAO(__FUNCTION__), $values);
}
Esempio n. 4
0
/**
 * Create a Contact Membership.
 *
 * This API is used for creating a Membership for a contact.
 * Required parameters : membership_type_id and status_id.
 *
 * @param array $params
 *   Array of name/value property values of civicrm_membership.
 *
 * @return array
 *   API result array.
 */
function civicrm_api3_membership_create($params)
{
    // check params for membership id during update
    if (!empty($params['id']) && !isset($params['skipStatusCal'])) {
        // Don't calculate status on existing membership - expect API use to pass them in
        // or leave unchanged.
        $params['skipStatusCal'] = 1;
    } else {
        // also check for status id if override is set (during add/update)
        if (!empty($params['is_override']) && empty($params['status_id'])) {
            return civicrm_api3_create_error('Status ID required');
        }
    }
    $values = array();
    _civicrm_api3_custom_format_params($params, $values, 'Membership');
    $params = array_merge($params, $values);
    // Fixme: This code belongs in the BAO
    if (empty($params['id']) || !empty($params['num_terms'])) {
        if (empty($params['id'])) {
            $calcDates = CRM_Member_BAO_MembershipType::getDatesForMembershipType($params['membership_type_id'], CRM_Utils_Array::value('join_date', $params), CRM_Utils_Array::value('start_date', $params), CRM_Utils_Array::value('end_date', $params), CRM_Utils_Array::value('num_terms', $params, 1));
        } else {
            $calcDates = CRM_Member_BAO_MembershipType::getRenewalDatesForMembershipType($params['id'], NULL, CRM_Utils_Array::value('membership_type_id', $params), $params['num_terms']);
        }
        foreach (array('join_date', 'start_date', 'end_date') as $date) {
            if (empty($params[$date]) && isset($calcDates[$date])) {
                $params[$date] = $calcDates[$date];
            }
        }
    }
    // Fixme: This code belongs in the BAO
    $action = CRM_Core_Action::ADD;
    // we need user id during add mode
    $ids = array();
    if (!empty($params['contact_id'])) {
        $ids['userId'] = $params['contact_id'];
    }
    //for edit membership id should be present
    if (!empty($params['id'])) {
        $ids['membership'] = $params['id'];
        $action = CRM_Core_Action::UPDATE;
    }
    //need to pass action to handle related memberships.
    $params['action'] = $action;
    if (empty($params['line_item']) && !empty($params['membership_type_id'])) {
        CRM_Price_BAO_LineItem::getLineItemArray($params, NULL, 'membership', $params['membership_type_id']);
    }
    $membershipBAO = CRM_Member_BAO_Membership::create($params, $ids, TRUE);
    if (array_key_exists('is_error', $membershipBAO)) {
        // In case of no valid status for given dates, $membershipBAO
        // is going to contain 'is_error' => "Error Message"
        return civicrm_api3_create_error(ts('The membership can not be saved, no valid membership status for given dates'));
    }
    $membership = array();
    _civicrm_api3_object_to_array($membershipBAO, $membership[$membershipBAO->id]);
    return civicrm_api3_create_success($membership, $params, 'Membership', 'create', $membershipBAO);
}
/**
 * Create a Event
 *
 * This API is used for creating a Event
 *
 * @param  array   $params   input parameters
 * Allowed @params array keys are:
 * {@getfields event_create}
 *
 * @return array API result Array.
 * @access public
 */
function civicrm_api3_event_create($params)
{
    _civicrm_api3_event_create_legacy_support_42($params);
    //format custom fields so they can be added
    $value = array();
    _civicrm_api3_custom_format_params($params, $values, 'Event');
    $params = array_merge($values, $params);
    require_once 'CRM/Event/BAO/Event.php';
    $eventBAO = CRM_Event_BAO_Event::create($params);
    $event = array();
    _civicrm_api3_object_to_array($eventBAO, $event[$eventBAO->id]);
    return civicrm_api3_create_success($event, $params);
}
Esempio n. 6
0
/**
 * Create an Event Participant.
 *
 * @param array $params
 *   An associative array of name/value property values of civicrm_participant.
 *
 * @return array
 *   API result array
 */
function civicrm_api3_participant_create($params)
{
    // Check that event id is not an template - should be done @ BAO layer.
    if (!empty($params['event_id'])) {
        $isTemplate = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $params['event_id'], 'is_template');
        if (!empty($isTemplate)) {
            return civicrm_api3_create_error(ts('Event templates are not meant to be registered.'));
        }
    }
    $values = $participant = array();
    _civicrm_api3_custom_format_params($params, $values, 'Participant');
    $params = array_merge($values, $params);
    $participantBAO = CRM_Event_BAO_Participant::create($params);
    if (empty($params['price_set_id']) && empty($params['id']) && !empty($params['fee_level'])) {
        _civicrm_api3_participant_createlineitem($params, $participantBAO);
    }
    _civicrm_api3_object_to_array($participantBAO, $participant[$participantBAO->id]);
    return civicrm_api3_create_success($participant, $params, 'Participant', 'create', $participantBAO);
}
Esempio n. 7
0
/**
 * Create or update a Contact.
 *
 * @param array $params
 *   Input parameters.
 *
 * @throws API_Exception
 *
 * @return array
 *   API Result Array
 */
function civicrm_api3_contact_create($params)
{
    $contactID = CRM_Utils_Array::value('contact_id', $params, CRM_Utils_Array::value('id', $params));
    if ($contactID && !empty($params['check_permissions']) && !CRM_Contact_BAO_Contact_Permission::allow($contactID, CRM_Core_Permission::EDIT)) {
        throw new \Civi\API\Exception\UnauthorizedException('Permission denied to modify contact record');
    }
    $dupeCheck = CRM_Utils_Array::value('dupe_check', $params, FALSE);
    $values = _civicrm_api3_contact_check_params($params, $dupeCheck);
    if ($values) {
        return $values;
    }
    if (!$contactID) {
        // If we get here, we're ready to create a new contact
        if (($email = CRM_Utils_Array::value('email', $params)) && !is_array($params['email'])) {
            $defLocType = CRM_Core_BAO_LocationType::getDefault();
            $params['email'] = array(1 => array('email' => $email, 'is_primary' => 1, 'location_type_id' => $defLocType->id ? $defLocType->id : 1));
        }
    }
    if (!empty($params['home_url'])) {
        $websiteTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Website', 'website_type_id');
        $params['website'] = array(1 => array('website_type_id' => key($websiteTypes), 'url' => $params['home_url']));
    }
    _civicrm_api3_greeting_format_params($params);
    $values = array();
    if (empty($params['contact_type']) && $contactID) {
        $params['contact_type'] = CRM_Contact_BAO_Contact::getContactType($contactID);
    }
    if (!isset($params['contact_sub_type']) && $contactID) {
        $params['contact_sub_type'] = CRM_Contact_BAO_Contact::getContactSubType($contactID);
    }
    _civicrm_api3_custom_format_params($params, $values, $params['contact_type'], $contactID);
    $params = array_merge($params, $values);
    //@todo we should just call basic_create here - but need to make contact:create accept 'id' on the bao
    $contact = _civicrm_api3_contact_update($params, $contactID);
    if (is_a($contact, 'CRM_Core_Error')) {
        throw new API_Exception($contact->_errors[0]['message']);
    } else {
        $values = array();
        _civicrm_api3_object_to_array_unique_fields($contact, $values[$contact->id]);
    }
    return civicrm_api3_create_success($values, $params, 'Contact', 'create');
}
Esempio n. 8
0
/**
 * Add or update a Contribution.
 *
 * @param array $params
 *   Input parameters.
 *
 * @throws API_Exception
 * @return array
 *   Api result array
 */
function civicrm_api3_contribution_create(&$params)
{
    $values = array();
    _civicrm_api3_custom_format_params($params, $values, 'Contribution');
    $params = array_merge($params, $values);
    if (CRM_Financial_BAO_FinancialType::isACLFinancialTypeStatus()) {
        if (empty($params['id'])) {
            $op = CRM_Core_Action::ADD;
        } else {
            if (empty($params['financial_type_id'])) {
                $params['financial_type_id'] = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $params['id'], 'financial_type_id');
            }
            $op = CRM_Core_Action::UPDATE;
        }
        CRM_Financial_BAO_FinancialType::getAvailableFinancialTypes($types, $op);
        if (!in_array($params['financial_type_id'], array_keys($types))) {
            return civicrm_api3_create_error('You do not have permission to create this contribution');
        }
    }
    if (!empty($params['id']) && !empty($params['contribution_status_id'])) {
        $error = array();
        //throw error for invalid status change such as setting completed back to pending
        //@todo this sort of validation belongs in the BAO not the API - if it is not an OK
        // action it needs to be blocked there. If it is Ok through a form it needs to be OK through the api
        CRM_Contribute_BAO_Contribution::checkStatusValidation(NULL, $params, $error);
        if (array_key_exists('contribution_status_id', $error)) {
            throw new API_Exception($error['contribution_status_id']);
        }
    }
    if (!empty($params['id']) && !empty($params['financial_type_id'])) {
        $error = array();
        CRM_Contribute_BAO_Contribution::checkFinancialTypeChange($params['financial_type_id'], $params['id'], $error);
        if (array_key_exists('financial_type_id', $error)) {
            throw new API_Exception($error['financial_type_id']);
        }
    }
    _civicrm_api3_contribution_create_legacy_support_45($params);
    // Make sure tax calculation is handled via api.
    // @todo this belongs in the BAO NOT the api.
    $params = CRM_Contribute_BAO_Contribution::checkTaxAmount($params);
    return _civicrm_api3_basic_create(_civicrm_api3_get_BAO(__FUNCTION__), $params, 'Contribution');
}
/**
 * create/update grant
 *
 * This API is used to create new grant or update any of the existing
 * In case of updating existing grant, id of that particular grant must
 * be in $params array.
 *
 * @param array $params  Associative array of property
 *                       name/value pairs to insert in new 'grant'
 *
 * @return array   grant array
 * {@getfields grant_create}
 * @access public
 */
function civicrm_api3_grant_create($params)
{
    $values = array();
    _civicrm_api3_custom_format_params($params, $values, 'Grant');
    $params = array_merge($values, $params);
    // BAO is non standard to we need to construct $ids array. Ideally we would fix BAO to accept $params without
    // id for standardisation
    $ids = array();
    if (CRM_Utils_Array::value('id', $params)) {
        $ids['grant'] = $params['id'];
    }
    $bao = CRM_GRANT_BAO_GRANT::create($params, $ids);
    if (is_null($bao)) {
        return civicrm_api3_create_error('Grant not created ');
    } else {
        $values = array();
        _civicrm_api3_object_to_array($bao, $values[$bao->id]);
        return civicrm_api3_create_success($values, $params, $bao, 'create');
    }
}
/**
 * Add or update a contribution
 *
 * @param  array   $params           (reference ) input parameters
 *
 * @return array  Api result array
 * @static void
 * @access public
 * @example ContributionCreate.php
 * {@getfields Contribution_create}
 */
function civicrm_api3_contribution_create(&$params)
{
    $values = array();
    _civicrm_api3_custom_format_params($params, $values, 'Contribution');
    $params = array_merge($params, $values);
    //legacy soft credit handling - recommended approach is chaining
    if (!empty($params['soft_credit_to'])) {
        $params['soft_credit'] = array(array('contact_id' => $params['soft_credit_to'], 'amount' => $params['total_amount']));
    }
    if (CRM_Utils_Array::value('id', $params) && CRM_Utils_Array::value('contribution_status_id', $params)) {
        $error = array();
        //throw error for invalid status change such as setting completed back to pending
        //@todo this sort of validation belongs in the BAO not the API - if it is not an OK
        // action it needs to be blocked there. If it is Ok through a form it needs to be OK through the api
        CRM_Contribute_BAO_Contribution::checkStatusValidation(NULL, $params, $error);
        if (array_key_exists('contribution_status_id', $error)) {
            throw new API_Exception($error['contribution_status_id']);
        }
    }
    return _civicrm_api3_basic_create(_civicrm_api3_get_BAO(__FUNCTION__), $params, 'Contribution');
}
Esempio n. 11
0
/**
 * Create a Event
 *
 * This API is used for creating a Event
 *
 * @param  array   $params   input parameters
 * Allowed @params array keys are:
 * {@getfields event_create}
 *
 * @return array API result Array.
 * @access public
 */
function civicrm_api3_event_create($params)
{
    civicrm_api3_verify_one_mandatory($params, NULL, array('event_type_id', 'template_id'));
    // Clone event from template
    if (!empty($params['template_id']) && empty($params['id'])) {
        $copy = CRM_Event_BAO_Event::copy($params['template_id']);
        $params['id'] = $copy->id;
        unset($params['template_id']);
        if (empty($params['is_template'])) {
            $params['is_template'] = 0;
        }
    }
    _civicrm_api3_event_create_legacy_support_42($params);
    //format custom fields so they can be added
    $values = array();
    _civicrm_api3_custom_format_params($params, $values, 'Event');
    $params = array_merge($values, $params);
    $eventBAO = CRM_Event_BAO_Event::create($params);
    $event = array();
    _civicrm_api3_object_to_array($eventBAO, $event[$eventBAO->id]);
    return civicrm_api3_create_success($event, $params);
}
/**
 * Create an Event Participant
 *
 * This API is used for creating a participants in an event.
 * Required parameters : event_id AND contact_id for new creation
 *                     : participant as name/value with participantid for edit
 *
 * @param   array  $params     an associative array of name/value property values of civicrm_participant
 *
 * @return array apiresult
 * {@getfields participant_create}
 * @access public
 */
function civicrm_api3_participant_create($params)
{
    //check that event id is not an template
    // note that check duplicate check was removed as it wasn't actually being called.
    //check contact exists removed as belongs @ wrapper layer
    if (CRM_Utils_Array::value('event_id', $params)) {
        $isTemplate = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $params['event_id'], 'is_template');
        if (!empty($isTemplate)) {
            return civicrm_api3_create_error(ts('Event templates are not meant to be registered'));
        }
    }
    $value = array();
    _civicrm_api3_custom_format_params($params, $values, 'Participant');
    $params = array_merge($values, $params);
    require_once 'CRM/Event/BAO/Participant.php';
    $participantBAO = CRM_Event_BAO_Participant::create($params);
    if (empty($params['price_set_id']) && empty($params['id']) && CRM_Utils_Array::value('fee_level', $params)) {
        _civicrm_api3_participant_createlineitem($params, $participantBAO);
    }
    _civicrm_api3_object_to_array($participantBAO, $participant[$participantBAO->id]);
    return civicrm_api3_create_success($participant, $params, 'participant', 'create', $participantBAO);
}
 /**
  * @deprecated - this function formats params according to v2 standards but
  * need to be sure about the impact of not calling it so retaining on the import class
  * take the input parameter list as specified in the data model and
  * convert it into the same format that we use in QF and BAO object
  *
  * @param array  $params       Associative array of property name/value
  *                             pairs to insert in new contact.
  * @param array  $values       The reformatted properties that we can use internally
  *
  * @param array  $create       Is the formatted Values array going to
  *                             be used for CRM_Member_BAO_Membership:create()
  *
  * @return array|error
  * @access public
  */
 function membership_format_params($params, &$values, $create = FALSE)
 {
     require_once 'api/v3/utils.php';
     $fields = CRM_Member_DAO_Membership::fields();
     _civicrm_api3_store_values($fields, $params, $values);
     $customFields = CRM_Core_BAO_CustomField::getFields('Membership');
     foreach ($params as $key => $value) {
         // ignore empty values or empty arrays etc
         if (CRM_Utils_System::isNull($value)) {
             continue;
         }
         //Handling Custom Data
         if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($key)) {
             $values[$key] = $value;
             $type = $customFields[$customFieldID]['html_type'];
             if ($type == 'CheckBox' || $type == 'Multi-Select' || $type == 'AdvMulti-Select') {
                 $mulValues = explode(',', $value);
                 $customOption = CRM_Core_BAO_CustomOption::getCustomOption($customFieldID, true);
                 $values[$key] = array();
                 foreach ($mulValues as $v1) {
                     foreach ($customOption as $customValueID => $customLabel) {
                         $customValue = $customLabel['value'];
                         if (strtolower($customLabel['label']) == strtolower(trim($v1)) || strtolower($customValue) == strtolower(trim($v1))) {
                             if ($type == 'CheckBox') {
                                 $values[$key][$customValue] = 1;
                             } else {
                                 $values[$key][] = $customValue;
                             }
                         }
                     }
                 }
             }
         }
         switch ($key) {
             case 'membership_contact_id':
                 if (!CRM_Utils_Rule::integer($value)) {
                     throw new Exception("contact_id not valid: {$value}");
                 }
                 $dao = new CRM_Core_DAO();
                 $qParams = array();
                 $svq = $dao->singleValueQuery("SELECT id FROM civicrm_contact WHERE id = {$value}", $qParams);
                 if (!$svq) {
                     throw new Exception("Invalid Contact ID: There is no contact record with contact_id = {$value}.");
                 }
                 $values['contact_id'] = $values['membership_contact_id'];
                 unset($values['membership_contact_id']);
                 break;
             case 'membership_type_id':
                 if (!CRM_Utils_Array::value($value, CRM_Member_PseudoConstant::membershipType())) {
                     throw new Exception('Invalid Membership Type Id');
                 }
                 $values[$key] = $value;
                 break;
             case 'membership_type':
                 $membershipTypeId = CRM_Utils_Array::key(ucfirst($value), CRM_Member_PseudoConstant::membershipType());
                 if ($membershipTypeId) {
                     if (CRM_Utils_Array::value('membership_type_id', $values) && $membershipTypeId != $values['membership_type_id']) {
                         throw new Exception('Mismatched membership Type and Membership Type Id');
                     }
                 } else {
                     throw new Exception('Invalid Membership Type');
                 }
                 $values['membership_type_id'] = $membershipTypeId;
                 break;
             case 'status_id':
                 if (!CRM_Utils_Array::value($value, CRM_Member_PseudoConstant::membershipStatus())) {
                     throw new Exception('Invalid Membership Status Id');
                 }
                 $values[$key] = $value;
                 break;
             case 'membership_status':
                 $membershipStatusId = CRM_Utils_Array::key(ucfirst($value), CRM_Member_PseudoConstant::membershipStatus());
                 if ($membershipStatusId) {
                     if (CRM_Utils_Array::value('status_id', $values) && $membershipStatusId != $values['status_id']) {
                         throw new Exception('Mismatched membership Status and Membership Status Id');
                     }
                 } else {
                     throw new Exception('Invalid Membership Status');
                 }
                 $values['status_id'] = $membershipStatusId;
                 break;
             default:
                 break;
         }
     }
     _civicrm_api3_custom_format_params($params, $values, 'Membership');
     if ($create) {
         // CRM_Member_BAO_Membership::create() handles membership_start_date,
         // membership_end_date and membership_source. So, if $values contains
         // membership_start_date, membership_end_date  or membership_source,
         // convert it to start_date, end_date or source
         $changes = array('membership_start_date' => 'start_date', 'membership_end_date' => 'end_date', 'membership_source' => 'source');
         foreach ($changes as $orgVal => $changeVal) {
             if (isset($values[$orgVal])) {
                 $values[$changeVal] = $values[$orgVal];
                 unset($values[$orgVal]);
             }
         }
     }
     return NULL;
 }
/**
 * Create a Contact Membership
 *
 * This API is used for creating a Membership for a contact.
 * Required parameters : membership_type_id and status_id.
 *
 * @param   array  $params     an associative array of name/value property values of civicrm_membership
 *
 * @return array of newly created membership property values.
 * {@getfields membership_create}
 * @access public
 */
function civicrm_api3_membership_create($params)
{
    // @todo shouldn't be required - should be handling by api.aliases & api.required in _spec
    civicrm_api3_verify_one_mandatory($params, NULL, array('membership_type_id', 'membership_type'));
    // check params for membership id during update
    if (CRM_Utils_Array::value('id', $params) && !isset($params['skipStatusCal'])) {
        //don't calculate dates on exisiting membership - expect API use to pass them in
        // or leave unchanged
        $params['skipStatusCal'] = 1;
    } else {
        // also check for status id if override is set (during add/update)
        if (isset($params['is_override']) && !CRM_Utils_Array::value('status_id', $params)) {
            return civicrm_api3_create_error('Status ID required');
        }
    }
    $values = array();
    $error = _civicrm_api3_membership_format_params($params, $values);
    if (civicrm_error($error)) {
        return $error;
    }
    _civicrm_api3_custom_format_params($params, $values, 'Membership');
    $params = array_merge($params, $values);
    $action = CRM_Core_Action::ADD;
    // we need user id during add mode
    $ids = array();
    if (CRM_Utils_Array::value('contact_id', $params)) {
        $ids['userId'] = $params['contact_id'];
    }
    //for edit membership id should be present
    if (CRM_Utils_Array::value('id', $params)) {
        $ids['membership'] = $params['id'];
        $action = CRM_Core_Action::UPDATE;
    }
    //need to pass action to handle related memberships.
    $params['action'] = $action;
    $membershipBAO = CRM_Member_BAO_Membership::create($params, $ids, TRUE);
    if (array_key_exists('is_error', $membershipBAO)) {
        // In case of no valid status for given dates, $membershipBAO
        // is going to contain 'is_error' => "Error Message"
        return civicrm_api3_create_error(ts('The membership can not be saved, no valid membership status for given dates'));
    }
    $membership = array();
    _civicrm_api3_object_to_array($membershipBAO, $membership[$membershipBAO->id]);
    return civicrm_api3_create_success($membership, $params, 'membership', 'create', $membershipBAO);
}
Esempio n. 15
0
/**
 * Format parameters for create action.
 *
 * @param array $params
 * @param $entity
 */
function _civicrm_api3_format_params_for_create(&$params, $entity)
{
    $nonGenericEntities = array('Contact', 'Individual', 'Household', 'Organization');
    $customFieldEntities = array_diff_key(CRM_Core_BAO_CustomQuery::$extendsMap, array_fill_keys($nonGenericEntities, 1));
    if (!array_key_exists($entity, $customFieldEntities)) {
        return;
    }
    $values = array();
    _civicrm_api3_custom_format_params($params, $values, $entity);
    $params = array_merge($params, $values);
}
Esempio n. 16
0
 /**
  * Format common params data to proper format to store.
  *
  * @param array $params
  *   Contain record values.
  * @param array $formatted
  *   Array of formatted data.
  * @param array $contactFields
  *   Contact DAO fields.
  */
 public function formatCommonData($params, &$formatted, &$contactFields)
 {
     $csType = array(CRM_Utils_Array::value('contact_type', $formatted));
     //CRM-5125
     //add custom fields for contact sub type
     if (!empty($this->_contactSubType)) {
         $csType = $this->_contactSubType;
     }
     if ($relCsType = CRM_Utils_Array::value('contact_sub_type', $formatted)) {
         $csType = $relCsType;
     }
     $customFields = CRM_Core_BAO_CustomField::getFields($formatted['contact_type'], FALSE, FALSE, $csType);
     $addressCustomFields = CRM_Core_BAO_CustomField::getFields('Address');
     $customFields = $customFields + $addressCustomFields;
     //if a Custom Email Greeting, Custom Postal Greeting or Custom Addressee is mapped, and no "Greeting / Addressee Type ID" is provided, then automatically set the type = Customized, CRM-4575
     $elements = array('email_greeting_custom' => 'email_greeting', 'postal_greeting_custom' => 'postal_greeting', 'addressee_custom' => 'addressee');
     foreach ($elements as $k => $v) {
         if (array_key_exists($k, $params) && !array_key_exists($v, $params)) {
             $label = key(CRM_Core_OptionGroup::values($v, TRUE, NULL, NULL, 'AND v.name = "Customized"'));
             $params[$v] = $label;
         }
     }
     //format date first
     $session = CRM_Core_Session::singleton();
     $dateType = $session->get("dateTypes");
     foreach ($params as $key => $val) {
         $customFieldID = CRM_Core_BAO_CustomField::getKeyID($key);
         if ($customFieldID && !array_key_exists($customFieldID, $addressCustomFields)) {
             //we should not update Date to null, CRM-4062
             if ($val && $customFields[$customFieldID]['data_type'] == 'Date') {
                 self::formatCustomDate($params, $formatted, $dateType, $key);
             } elseif ($customFields[$customFieldID]['data_type'] == 'Boolean') {
                 if (empty($val) && !is_numeric($val) && $this->_onDuplicate == CRM_Import_Parser::DUPLICATE_FILL) {
                     //retain earlier value when Import mode is `Fill`
                     unset($params[$key]);
                 } else {
                     $params[$key] = CRM_Utils_String::strtoboolstr($val);
                 }
             }
             if ($key == 'birth_date' && $val) {
                 CRM_Utils_Date::convertToDefaultDate($params, $dateType, $key);
             } elseif ($key == 'deceased_date' && $val) {
                 CRM_Utils_Date::convertToDefaultDate($params, $dateType, $key);
             } elseif ($key == 'is_deceased' && $val) {
                 $params[$key] = CRM_Utils_String::strtoboolstr($val);
             } elseif ($key == 'gender') {
                 //CRM-4360
                 $params[$key] = $this->checkGender($val);
             }
         }
     }
     //now format custom data.
     foreach ($params as $key => $field) {
         if (is_array($field)) {
             $isAddressCustomField = FALSE;
             foreach ($field as $value) {
                 $break = FALSE;
                 if (is_array($value)) {
                     foreach ($value as $name => $testForEmpty) {
                         if ($addressCustomFieldID = CRM_Core_BAO_CustomField::getKeyID($name)) {
                             $isAddressCustomField = TRUE;
                             break;
                         }
                         // check if $value does not contain IM provider or phoneType
                         if (($name !== 'phone_type_id' || $name !== 'provider_id') && ($testForEmpty === '' || $testForEmpty == NULL)) {
                             $break = TRUE;
                             break;
                         }
                     }
                 } else {
                     $break = TRUE;
                 }
                 if (!$break) {
                     require_once 'CRM/Utils/DeprecatedUtils.php';
                     _civicrm_api3_deprecated_add_formatted_param($value, $formatted);
                 }
             }
             if (!$isAddressCustomField) {
                 continue;
             }
         }
         $formatValues = array($key => $field);
         if ($key !== 'preferred_communication_method' && array_key_exists($key, $contactFields)) {
             // due to merging of individual table and
             // contact table, we need to avoid
             // preferred_communication_method forcefully
             $formatValues['contact_type'] = $formatted['contact_type'];
         }
         if ($key == 'id' && isset($field)) {
             $formatted[$key] = $field;
         }
         require_once 'CRM/Utils/DeprecatedUtils.php';
         _civicrm_api3_deprecated_add_formatted_param($formatValues, $formatted);
         //Handling Custom Data
         // note: Address custom fields will be handled separately inside _civicrm_api3_deprecated_add_formatted_param
         if (($customFieldID = CRM_Core_BAO_CustomField::getKeyID($key)) && array_key_exists($customFieldID, $customFields) && !array_key_exists($customFieldID, $addressCustomFields)) {
             $extends = CRM_Utils_Array::value('extends', $customFields[$customFieldID]);
             $htmlType = CRM_Utils_Array::value('html_type', $customFields[$customFieldID]);
             switch ($htmlType) {
                 case 'Select':
                 case 'Radio':
                 case 'Autocomplete-Select':
                     if ($customFields[$customFieldID]['data_type'] == 'String') {
                         $customOption = CRM_Core_BAO_CustomOption::getCustomOption($customFieldID, TRUE);
                         foreach ($customOption as $customFldID => $customValue) {
                             $val = CRM_Utils_Array::value('value', $customValue);
                             $label = CRM_Utils_Array::value('label', $customValue);
                             $label = strtolower($label);
                             $value = strtolower(trim($formatted[$key]));
                             if ($value == $label || $value == strtolower($val)) {
                                 $params[$key] = $formatted[$key] = $val;
                             }
                         }
                     }
                     break;
                 case 'CheckBox':
                 case 'AdvMulti-Select':
                 case 'Multi-Select':
                     if (!empty($formatted[$key]) && !empty($params[$key])) {
                         $mulValues = explode(',', $formatted[$key]);
                         $customOption = CRM_Core_BAO_CustomOption::getCustomOption($customFieldID, TRUE);
                         $formatted[$key] = array();
                         $params[$key] = array();
                         foreach ($mulValues as $v1) {
                             foreach ($customOption as $v2) {
                                 if (strtolower($v2['label']) == strtolower(trim($v1)) || strtolower($v2['value']) == strtolower(trim($v1))) {
                                     if ($htmlType == 'CheckBox') {
                                         $params[$key][$v2['value']] = $formatted[$key][$v2['value']] = 1;
                                     } else {
                                         $params[$key][] = $formatted[$key][] = $v2['value'];
                                     }
                                 }
                             }
                         }
                     }
                     break;
             }
         }
     }
     if (($customFieldID = CRM_Core_BAO_CustomField::getKeyID($key)) && array_key_exists($customFieldID, $customFields) && !array_key_exists($customFieldID, $addressCustomFields)) {
         // @todo calling api functions directly is not supported
         _civicrm_api3_custom_format_params($params, $formatted, $extends);
     }
     // to check if not update mode and unset the fields with empty value.
     if (!$this->_updateWithId && array_key_exists('custom', $formatted)) {
         foreach ($formatted['custom'] as $customKey => $customvalue) {
             if (empty($formatted['custom'][$customKey][-1]['is_required'])) {
                 $formatted['custom'][$customKey][-1]['is_required'] = $customFields[$customKey]['is_required'];
             }
             $emptyValue = CRM_Utils_Array::value('value', $customvalue[-1]);
             if (!isset($emptyValue)) {
                 unset($formatted['custom'][$customKey]);
             }
         }
     }
     // parse street address, CRM-5450
     if ($this->_parseStreetAddress) {
         if (array_key_exists('address', $formatted) && is_array($formatted['address'])) {
             foreach ($formatted['address'] as $instance => &$address) {
                 $streetAddress = CRM_Utils_Array::value('street_address', $address);
                 if (empty($streetAddress)) {
                     continue;
                 }
                 // parse address field.
                 $parsedFields = CRM_Core_BAO_Address::parseStreetAddress($streetAddress);
                 //street address consider to be parsed properly,
                 //If we get street_name and street_number.
                 if (empty($parsedFields['street_name']) || empty($parsedFields['street_number'])) {
                     $parsedFields = array_fill_keys(array_keys($parsedFields), '');
                 }
                 // merge parse address w/ main address block.
                 $address = array_merge($address, $parsedFields);
             }
         }
     }
 }
Esempio n. 17
0
/**
 * take the input parameter list as specified in the data model and
 * convert it into the same format that we use in QF and BAO object
 *
 * @param array $params Associative array of property name/value
 *                             pairs to insert in new contact.
 * @param array $values The reformatted properties that we can use internally
 *                            '
 *
 * @throws Exception
 * @return array|CRM_Error
 * @access public
 */
function _civicrm_api3_relationship_format_params($params, &$values)
{
    // copy all the relationship fields as is
    $fields = CRM_Contact_DAO_Relationship::fields();
    _civicrm_api3_store_values($fields, $params, $values);
    $relationTypes = CRM_Core_PseudoConstant::relationshipType('name');
    if (!empty($params['id'])) {
        $relation = new CRM_Contact_BAO_Relationship();
        $relation->id = $params['id'];
        if (!$relation->find(TRUE)) {
            throw new Exception('Relationship id is not valid');
        } else {
            if (isset($params['contact_id_a']) && $params['contact_id_a'] != $relation->contact_id_a || isset($params['contact_id_b']) && $params['contact_id_b'] != $relation->contact_id_b) {
                throw new Exception('Cannot change the contacts once relationship has been created');
            } else {
                // since the BAO function is not std & won't accept just 'id' (aargh) let's
                // at least return our BAO here
                $values = array();
                _civicrm_api3_object_to_array($relation, $values);
                $values = array_merge($values, $params);
                // and we need to reformat our date fields....
                $dateFields = array('start_date', 'end_date');
                foreach ($dateFields as $dateField) {
                    $values[$dateField] = CRM_Utils_Date::processDate($values[$dateField]);
                }
            }
        }
    }
    foreach ($params as $key => $value) {
        // ignore empty values or empty arrays etc
        if (CRM_Utils_System::isNull($value)) {
            continue;
        }
        switch ($key) {
            case 'contact_id_a':
            case 'contact_id_b':
                if (!CRM_Utils_Rule::integer($value)) {
                    throw new Exception("contact_id not valid: {$value}");
                }
                $dao = new CRM_Core_DAO();
                $qParams = array();
                $svq = $dao->singleValueQuery("SELECT id FROM civicrm_contact WHERE id = {$value}", $qParams);
                if (!$svq) {
                    throw new Exception("Invalid Contact ID: There is no contact record with contact_id = {$value}.");
                }
                break;
            case 'relationship_type':
                foreach ($relationTypes as $relTypId => $relValue) {
                    if (CRM_Utils_Array::key(ucfirst($value), $relValue)) {
                        $relationshipTypeId = $relTypId;
                        break;
                    }
                }
                if ($relationshipTypeId) {
                    if (!empty($values['relationship_type_id']) && $relationshipTypeId != $values['relationship_type_id']) {
                        throw new Exception('Mismatched Relationship Type and Relationship Type Id');
                    }
                    $values['relationship_type_id'] = $params['relationship_type_id'] = $relationshipTypeId;
                } else {
                    throw new Exception('Invalid Relationship Type');
                }
            case 'relationship_type_id':
                if ($key == 'relationship_type_id' && !array_key_exists($value, $relationTypes)) {
                    throw new Exception("{$key} not a valid: {$value}");
                }
                // execute for both relationship_type and relationship_type_id
                $relation = $relationTypes[$params['relationship_type_id']];
                if (!empty($params['contact_id_a']) && $relation['contact_type_a'] && $relation['contact_type_a'] != CRM_Contact_BAO_Contact::getContactType($params['contact_id_a'])) {
                    throw new Exception("Contact ID :{$params['contact_id_a']} is not of contact type {$relation['contact_type_a']}");
                }
                if (!empty($params['contact_id_b']) && $relation['contact_type_b'] && $relation['contact_type_b'] != CRM_Contact_BAO_Contact::getContactType($params['contact_id_b'])) {
                    throw new Exception("Contact ID :{$params['contact_id_b']} is not of contact type {$relation['contact_type_b']}");
                }
                break;
            default:
                break;
        }
    }
    if (array_key_exists('note', $params)) {
        $values['note'] = $params['note'];
    }
    _civicrm_api3_custom_format_params($params, $values, 'Relationship');
    return array();
}
/**
 * take the input parameter list as specified in the data model and
 * convert it into the same format that we use in QF and BAO object
 *
 * @param array  $params       Associative array of property name/value
 *                             pairs to insert in new contact.
 * @param array  $values       The reformatted properties that we can use internally
 *                            '
 *
 * @return array|CRM_Error
 * @access public
 */
function _civicrm_api3_relationship_format_params($params, &$values)
{
    // copy all the relationship fields as is
    $fields = CRM_Contact_DAO_Relationship::fields();
    _civicrm_api3_store_values($fields, $params, $values);
    $relationTypes = CRM_Core_PseudoConstant::relationshipType('name');
    foreach ($params as $key => $value) {
        // ignore empty values or empty arrays etc
        require_once 'CRM/Utils/System.php';
        if (CRM_Utils_System::isNull($value)) {
            continue;
        }
        switch ($key) {
            case 'contact_id_a':
            case 'contact_id_b':
                require_once 'CRM/Utils/Rule.php';
                if (!CRM_Utils_Rule::integer($value)) {
                    throw new Exception("contact_id not valid: {$value}");
                }
                $dao = new CRM_Core_DAO();
                $qParams = array();
                $svq = $dao->singleValueQuery("SELECT id FROM civicrm_contact WHERE id = {$value}", $qParams);
                if (!$svq) {
                    throw new Exception("Invalid Contact ID: There is no contact record with contact_id = {$value}.");
                }
                break;
            case 'relationship_type':
                foreach ($relationTypes as $relTypId => $relValue) {
                    if (CRM_Utils_Array::key(ucfirst($value), $relValue)) {
                        $relationshipTypeId = $relTypId;
                        break;
                    }
                }
                if ($relationshipTypeId) {
                    if (CRM_Utils_Array::value('relationship_type_id', $values) && $relationshipTypeId != $values['relationship_type_id']) {
                        throw new Exception('Mismatched Relationship Type and Relationship Type Id');
                    }
                    $values['relationship_type_id'] = $params['relationship_type_id'] = $relationshipTypeId;
                } else {
                    throw new Exception('Invalid Relationship Type');
                }
            case 'relationship_type_id':
                if ($key == 'relationship_type_id' && !array_key_exists($value, $relationTypes)) {
                    throw new Exception("{$key} not a valid: {$value}");
                }
                // execute for both relationship_type and relationship_type_id
                $relation = $relationTypes[$params['relationship_type_id']];
                if ($relation['contact_type_a'] && $relation['contact_type_a'] != CRM_Contact_BAO_Contact::getContactType($params['contact_id_a'])) {
                    throw new Exception("Contact ID :{$params['contact_id_a']} is not of contact type {$relation['contact_type_a']}");
                }
                if ($relation['contact_type_b'] && $relation['contact_type_b'] != CRM_Contact_BAO_Contact::getContactType($params['contact_id_b'])) {
                    throw new Exception("Contact ID :{$params['contact_id_b']} is not of contact type {$relation['contact_type_b']}");
                }
                break;
            default:
                break;
        }
    }
    if (array_key_exists('note', $params)) {
        $values['note'] = $params['note'];
    }
    _civicrm_api3_custom_format_params($params, $values, 'Relationship');
    return array();
}
/**
 * Create or update a contact (note you should always call this via civicrm_api() & never directly)
 *
 * @param  array   $params   input parameters
 *
 * Allowed @params array keys are:
 * {@getfields contact_create}
 *
 *
 * @example ContactCreate.php Example of Create Call
 *
 * @return array  API Result Array
 *
 * @static void
 * @access public
 */
function civicrm_api3_contact_create($params)
{
    $contactID = CRM_Utils_Array::value('contact_id', $params, CRM_Utils_Array::value('id', $params));
    $dupeCheck = CRM_Utils_Array::value('dupe_check', $params, FALSE);
    $values = _civicrm_api3_contact_check_params($params, $dupeCheck);
    if ($values) {
        return $values;
    }
    if (empty($contactID)) {
        // If we get here, we're ready to create a new contact
        if (($email = CRM_Utils_Array::value('email', $params)) && !is_array($params['email'])) {
            require_once 'CRM/Core/BAO/LocationType.php';
            $defLocType = CRM_Core_BAO_LocationType::getDefault();
            $params['email'] = array(1 => array('email' => $email, 'is_primary' => 1, 'location_type_id' => $defLocType->id ? $defLocType->id : 1));
        }
    }
    if (CRM_Utils_Array::value('home_url', $params)) {
        require_once 'CRM/Core/PseudoConstant.php';
        $websiteTypes = CRM_Core_PseudoConstant::websiteType();
        $params['website'] = array(1 => array('website_type_id' => key($websiteTypes), 'url' => $params['home_url']));
    }
    if (isset($params['suffix_id']) && !is_numeric($params['suffix_id'])) {
        $params['suffix_id'] = array_search($params['suffix_id'], CRM_Core_PseudoConstant::individualSuffix());
    }
    if (isset($params['prefix_id']) && !is_numeric($params['prefix_id'])) {
        $params['prefix_id'] = array_search($params['prefix_id'], CRM_Core_PseudoConstant::individualPrefix());
    }
    if (isset($params['gender_id']) && !is_numeric($params['gender_id'])) {
        $params['gender_id'] = array_search($params['gender_id'], CRM_Core_PseudoConstant::gender());
    }
    $error = _civicrm_api3_greeting_format_params($params);
    if (civicrm_error($error)) {
        return $error;
    }
    $values = array();
    $entityId = $contactID;
    if (!CRM_Utils_Array::value('contact_type', $params) && $entityId) {
        $params['contact_type'] = CRM_Contact_BAO_Contact::getContactType($entityId);
    }
    if (!isset($params['contact_sub_type']) && $entityId) {
        require_once 'CRM/Contact/BAO/Contact.php';
        $params['contact_sub_type'] = CRM_Contact_BAO_Contact::getContactSubType($entityId);
    }
    _civicrm_api3_custom_format_params($params, $values, $params['contact_type'], $entityId);
    $params = array_merge($params, $values);
    $contact = _civicrm_api3_contact_update($params, $contactID);
    if (is_a($contact, 'CRM_Core_Error')) {
        return civicrm_api3_create_error($contact->_errors[0]['message']);
    } else {
        $values = array();
        _civicrm_api3_object_to_array_unique_fields($contact, $values[$contact->id]);
    }
    return civicrm_api3_create_success($values, $params, 'Contact', 'create');
}
Esempio n. 20
0
/**
 * Creates or updates an Activity.
 *
 * @param array $params
 *   Array per getfields documentation.
 *
 * @throws API_Exception
 * @return array
 *   API result array
 */
function civicrm_api3_activity_create($params)
{
    if (empty($params['id'])) {
        // an update does not require any mandatory parameters
        civicrm_api3_verify_one_mandatory($params, NULL, array('activity_name', 'activity_type_id', 'activity_label'));
    }
    // check for various error and required conditions
    // note that almost all the processing in there should be managed by the wrapper layer
    // & should be removed - needs testing
    $errors = _civicrm_api3_activity_check_params($params);
    // this should not be required as should throw exception rather than return errors -
    //needs testing
    if (!empty($errors)) {
        return $errors;
    }
    // processing for custom data
    $values = $activityArray = array();
    _civicrm_api3_custom_format_params($params, $values, 'Activity');
    if (!empty($values['custom'])) {
        $params['custom'] = $values['custom'];
    }
    // this should be set as a default rather than hard coded
    // needs testing
    $params['skipRecentView'] = TRUE;
    // If this is a case activity, see if there is an existing activity
    // and set it as an old revision. Also retrieve details we'll need.
    // this handling should all be moved to the BAO layer
    $case_id = '';
    $createRevision = FALSE;
    $oldActivityValues = array();
    // Lookup case id if not supplied
    if (!isset($params['case_id']) && !empty($params['id'])) {
        $params['case_id'] = CRM_Core_DAO::singleValueQuery("SELECT case_id FROM civicrm_case_activity WHERE activity_id = " . (int) $params['id']);
    }
    if (!empty($params['case_id'])) {
        $case_id = $params['case_id'];
        if (!empty($params['id'])) {
            $oldActivityParams = array('id' => $params['id']);
            if (!$oldActivityValues) {
                CRM_Activity_BAO_Activity::retrieve($oldActivityParams, $oldActivityValues);
            }
            if (empty($oldActivityValues)) {
                throw new API_Exception(ts("Unable to locate existing activity."));
            } else {
                $activityDAO = new CRM_Activity_DAO_Activity();
                $activityDAO->id = $params['id'];
                $activityDAO->is_current_revision = 0;
                if (!$activityDAO->save()) {
                    if (is_object($activityDAO)) {
                        $activityDAO->free();
                    }
                    throw new API_Exception(ts("Unable to revision existing case activity."));
                }
                $createRevision = TRUE;
            }
        }
    }
    $deleteActivityAssignment = FALSE;
    if (isset($params['assignee_contact_id'])) {
        $deleteActivityAssignment = TRUE;
    }
    $deleteActivityTarget = FALSE;
    if (isset($params['target_contact_id'])) {
        $deleteActivityTarget = TRUE;
    }
    // this should all be handled at the BAO layer
    $params['deleteActivityAssignment'] = CRM_Utils_Array::value('deleteActivityAssignment', $params, $deleteActivityAssignment);
    $params['deleteActivityTarget'] = CRM_Utils_Array::value('deleteActivityTarget', $params, $deleteActivityTarget);
    if ($case_id && $createRevision) {
        // This is very similar to the copy-to-case action.
        if (!CRM_Utils_Array::crmIsEmptyArray($oldActivityValues['target_contact'])) {
            $oldActivityValues['targetContactIds'] = implode(',', array_unique($oldActivityValues['target_contact']));
        }
        if (!CRM_Utils_Array::crmIsEmptyArray($oldActivityValues['assignee_contact'])) {
            $oldActivityValues['assigneeContactIds'] = implode(',', array_unique($oldActivityValues['assignee_contact']));
        }
        $oldActivityValues['mode'] = 'copy';
        $oldActivityValues['caseID'] = $case_id;
        $oldActivityValues['activityID'] = $oldActivityValues['id'];
        $oldActivityValues['contactID'] = $oldActivityValues['source_contact_id'];
        $copyToCase = CRM_Activity_Page_AJAX::_convertToCaseActivity($oldActivityValues);
        if (empty($copyToCase['error_msg'])) {
            // now fix some things that are different from copy-to-case
            // then fall through to the create below to update with the passed in params
            $params['id'] = $copyToCase['newId'];
            $params['is_auto'] = 0;
            $params['original_id'] = empty($oldActivityValues['original_id']) ? $oldActivityValues['id'] : $oldActivityValues['original_id'];
        } else {
            throw new API_Exception(ts("Unable to create new revision of case activity."));
        }
    }
    // create activity
    $activityBAO = CRM_Activity_BAO_Activity::create($params);
    if (isset($activityBAO->id)) {
        if ($case_id && !$createRevision) {
            // If this is a brand new case activity we need to add this
            $caseActivityParams = array('activity_id' => $activityBAO->id, 'case_id' => $case_id);
            CRM_Case_BAO_Case::processCaseActivity($caseActivityParams);
        }
        _civicrm_api3_object_to_array($activityBAO, $activityArray[$activityBAO->id]);
        return civicrm_api3_create_success($activityArray, $params, 'Activity', 'get', $activityBAO);
    }
}
/**
 * Creates or updates an Activity. See the example for usage
 *
 * @param array  $params       Associative array of property name/value
 *                             pairs for the activity.
 * {@getfields activity_create}
 *
 * @return array Array containing 'is_error' to denote success or failure and details of the created activity
 *
 * @example ActivityCreate.php Standard create example
 * @example Activity/ContactRefCustomField.php Create example including setting a contact reference custom field
 * {@example ActivityCreate.php 0}
 *
 */
function civicrm_api3_activity_create($params)
{
    if (!CRM_Utils_Array::value('id', $params)) {
        // an update does not require any mandatory parameters
        civicrm_api3_verify_one_mandatory($params, NULL, array('activity_name', 'activity_type_id', 'activity_label'));
    }
    $errors = array();
    // check for various error and required conditions
    $errors = _civicrm_api3_activity_check_params($params);
    if (!empty($errors)) {
        return $errors;
    }
    // processing for custom data
    $values = array();
    _civicrm_api3_custom_format_params($params, $values, 'Activity');
    if (!empty($values['custom'])) {
        $params['custom'] = $values['custom'];
    }
    $params['skipRecentView'] = TRUE;
    // If this is a case activity, see if there is an existing activity
    // and set it as an old revision. Also retrieve details we'll need.
    $case_id = '';
    $createRevision = FALSE;
    $oldActivityValues = array();
    if (CRM_Utils_Array::value('case_id', $params)) {
        $case_id = $params['case_id'];
        if (CRM_Utils_Array::value('id', $params)) {
            $oldActivityParams = array('id' => $params['id']);
            if (!$oldActivityValues) {
                CRM_Activity_BAO_Activity::retrieve($oldActivityParams, $oldActivityValues);
            }
            if (empty($oldActivityValues)) {
                return civicrm_api3_create_error(ts("Unable to locate existing activity."), NULL, CRM_Core_DAO::$_nullObject);
            } else {
                require_once 'CRM/Activity/DAO/Activity.php';
                $activityDAO = new CRM_Activity_DAO_Activity();
                $activityDAO->id = $params['id'];
                $activityDAO->is_current_revision = 0;
                if (!$activityDAO->save()) {
                    return civicrm_api3_create_error(ts("Unable to revision existing case activity."), NULL, $activityDAO);
                }
                $createRevision = TRUE;
            }
        }
    }
    $deleteActivityAssignment = FALSE;
    if (isset($params['assignee_contact_id'])) {
        $deleteActivityAssignment = TRUE;
    }
    $deleteActivityTarget = FALSE;
    if (isset($params['target_contact_id'])) {
        $deleteActivityTarget = TRUE;
    }
    $params['deleteActivityAssignment'] = CRM_Utils_Array::value('deleteActivityAssignment', $params, $deleteActivityAssignment);
    $params['deleteActivityTarget'] = CRM_Utils_Array::value('deleteActivityTarget', $params, $deleteActivityTarget);
    if ($case_id && $createRevision) {
        // This is very similar to the copy-to-case action.
        if (!CRM_Utils_Array::crmIsEmptyArray($oldActivityValues['target_contact'])) {
            $oldActivityValues['targetContactIds'] = implode(',', array_unique($oldActivityValues['target_contact']));
        }
        if (!CRM_Utils_Array::crmIsEmptyArray($oldActivityValues['assignee_contact'])) {
            $oldActivityValues['assigneeContactIds'] = implode(',', array_unique($oldActivityValues['assignee_contact']));
        }
        $oldActivityValues['mode'] = 'copy';
        $oldActivityValues['caseID'] = $case_id;
        $oldActivityValues['activityID'] = $oldActivityValues['id'];
        $oldActivityValues['contactID'] = $oldActivityValues['source_contact_id'];
        require_once 'CRM/Activity/Page/AJAX.php';
        $copyToCase = CRM_Activity_Page_AJAX::_convertToCaseActivity($oldActivityValues);
        if (empty($copyToCase['error_msg'])) {
            // now fix some things that are different from copy-to-case
            // then fall through to the create below to update with the passed in params
            $params['id'] = $copyToCase['newId'];
            $params['is_auto'] = 0;
            $params['original_id'] = empty($oldActivityValues['original_id']) ? $oldActivityValues['id'] : $oldActivityValues['original_id'];
        } else {
            return civicrm_api3_create_error(ts("Unable to create new revision of case activity."), NULL, CRM_Core_DAO::$_nullObject);
        }
    }
    // create activity
    $activityBAO = CRM_Activity_BAO_Activity::create($params);
    if (isset($activityBAO->id)) {
        if ($case_id && !$createRevision) {
            // If this is a brand new case activity we need to add this
            $caseActivityParams = array('activity_id' => $activityBAO->id, 'case_id' => $case_id);
            require_once 'CRM/Case/BAO/Case.php';
            CRM_Case_BAO_Case::processCaseActivity($caseActivityParams);
        }
        _civicrm_api3_object_to_array($activityBAO, $activityArray[$activityBAO->id]);
        return civicrm_api3_create_success($activityArray, $params, 'activity', 'get', $activityBAO);
    }
}
Esempio n. 22
0
/**
 * Create or update a ContributionRecur.
 *
 * @param array $params
 *   Array per getfields metadata.
 *
 * @return array
 *   api result array
 */
function civicrm_api3_contribution_recur_create($params)
{
    _civicrm_api3_custom_format_params($params, $values, 'ContributionRecur');
    $params = array_merge($params, $values);
    return _civicrm_api3_basic_create(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}