/**
 * Create a Membership Status
 *
 * This API is used for creating a Membership Status
 *
 * @param   array  $params  an associative array of name/value property values of civicrm_membership_status
 *
 * @return array of newly created membership status property values.
 * {@getfields MembershipStatus_create}
 * @access public
 */
function civicrm_api3_membership_status_create($params)
{
    civicrm_api3_verify_one_mandatory($params, 'CRM_Member_DAO_MembershipStatus', array('name', 'label'));
    //move before verifiy? DAO check requires?
    if (empty($params['name'])) {
        $params['name'] = CRM_Utils_Array::value('label', $params);
    }
    //don't allow duplicate names.
    require_once 'CRM/Member/DAO/MembershipStatus.php';
    $status = new CRM_Member_DAO_MembershipStatus();
    $status->name = $params['name'];
    if ($status->find(TRUE)) {
        return civicrm_api3_create_error(ts('A membership status with this name already exists.'));
    }
    require_once 'CRM/Member/BAO/MembershipStatus.php';
    $ids = array();
    $membershipStatusBAO = CRM_Member_BAO_MembershipStatus::add($params, $ids);
    if (is_a($membershipStatusBAO, 'CRM_Core_Error')) {
        return civicrm_api3_create_error("Membership is not created");
    } else {
        $values = array();
        $values['id'] = $membershipStatusBAO->id;
        $values['is_error'] = 0;
        return civicrm_api3_create_success($values, $params);
    }
}
/**
 * Create a new ActionSchedule.
 *
 * @param array $params
 *
 * @return array
 */
function civicrm_api3_action_schedule_create($params)
{
    civicrm_api3_verify_one_mandatory($params, NULL, array('start_action_date', 'absolute_date'));
    if (!array_key_exists('name', $params) && !array_key_exists('id', $params)) {
        $params['name'] = CRM_Utils_String::munge($params['title']);
    }
    return _civicrm_api3_basic_create(_civicrm_api3_get_BAO(__FUNCTION__), $params, 'ActionSchedule');
}
Example #3
0
/**
 * Creates/Updates a new Dashboard Contact Entry.
 *
 * @param array $params
 *
 * @return array
 */
function civicrm_api3_dashboard_contact_create($params)
{
    if (empty($params['id'])) {
        civicrm_api3_verify_one_mandatory($params, NULL, array('dashboard_id'));
    }
    $errors = _civicrm_api3_dashboard_contact_check_params($params);
    if ($errors !== NULL) {
        return $errors;
    }
    return _civicrm_api3_basic_create(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}
Example #4
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']);
    }
    _civicrm_api3_event_create_legacy_support_42($params);
    return _civicrm_api3_basic_create(_civicrm_api3_get_BAO(__FUNCTION__), $params, 'Event');
}
/**
 * Creates or updates an Dashlet.
 *
 * @param array  $params       Associative array of property name/value
 *                             pairs for the Dashlet.
 *
 * @return array Array containing 'is_error' to denote success or failure and details of the created activity
 *
 */
function civicrm_api3_dashboard_create($params)
{
    if (empty($params['id'])) {
        civicrm_api3_verify_one_mandatory($params, NULL, array('name', 'label', 'url', 'fullscreen_url'));
    }
    // create dashboard element
    $dashboardBAO = CRM_Core_BAO_Dashboard::addDashlet($params);
    if (isset($dashboardBAO->id)) {
        _civicrm_api3_object_to_array($dashboardBAO, $dashboardArray[$dashboardBAO->id]);
        return civicrm_api3_create_success($dashboardArray, $params, 'dashboard', 'create', $dashboardBAO);
    }
}
/**
 * Defines 'uf field' within a group.
 *
 * @param array $params
 *   Array per getfields metadata.
 *
 * @throws API_Exception
 *
 * @return array
 *   Newly created $ufFieldArray
 */
function civicrm_api3_uf_field_create($params)
{
    civicrm_api3_verify_one_mandatory($params, NULL, array('field_name', 'uf_group_id'));
    $groupId = CRM_Utils_Array::value('uf_group_id', $params);
    if ((int) $groupId < 1) {
        throw new API_Exception('Params must be a field_name-carrying array and a positive integer.');
    }
    $field_type = CRM_Utils_Array::value('field_type', $params);
    $field_name = CRM_Utils_Array::value('field_name', $params);
    $location_type_id = CRM_Utils_Array::value('location_type_id', $params, CRM_Utils_Array::value('website_type_id', $params));
    $phone_type = CRM_Utils_Array::value('phone_type_id', $params, CRM_Utils_Array::value('phone_type', $params));
    if (!CRM_Core_BAO_UFField::isValidFieldName($field_name)) {
        throw new API_Exception('The field_name is not valid');
    }
    $params['field_name'] = array($field_type, $field_name, $location_type_id, $phone_type);
    if (!CRM_Utils_Array::value('group_id', $params)) {
        $params['group_id'] = $groupId;
    }
    $ids = $ufFieldArray = array();
    $ids['uf_group'] = $groupId;
    $fieldId = CRM_Utils_Array::value('id', $params);
    if (!empty($fieldId)) {
        $UFField = new CRM_Core_BAO_UFField();
        $UFField->id = $fieldId;
        if ($UFField->find(TRUE)) {
            $ids['uf_group'] = $UFField->uf_group_id;
            if (!CRM_Utils_Array::value('group_id', $params)) {
                // this copied here from previous api function - not sure if required
                $params['group_id'] = $UFField->uf_group_id;
            }
        } else {
            throw new API_Exception("there is no field for this fieldId");
        }
        $ids['uf_field'] = $fieldId;
    }
    if (CRM_Core_BAO_UFField::duplicateField($params, $ids)) {
        throw new API_Exception("The field was not added. It already exists in this profile.");
    }
    //@todo why is this even optional? Surely weight should just be 'managed' ??
    if (CRM_Utils_Array::value('option.autoweight', $params, TRUE)) {
        $params['weight'] = CRM_Core_BAO_UFField::autoWeight($params);
    }
    $ufField = CRM_Core_BAO_UFField::add($params, $ids);
    $fieldsType = CRM_Core_BAO_UFGroup::calculateGroupType($groupId, TRUE);
    CRM_Core_BAO_UFGroup::updateGroupTypes($groupId, $fieldsType);
    _civicrm_api3_object_to_array($ufField, $ufFieldArray[$ufField->id]);
    civicrm_api3('profile', 'getfields', array('cache_clear' => TRUE));
    return civicrm_api3_create_success($ufFieldArray, $params);
}
Example #7
0
/**
 * Get the list of voters (respondents, yet to record survey response) for a survey
 *
 * @param  array   $params           (reference ) input parameters
 *
 * @return array (reference )        contact_id
 * @static void
 * @access public
 */
function &civicrm_api3_survey_voter_get($params)
{
    civicrm_api3_verify_one_mandatory($params, 'CRM_Campaign_BAO_Survey', array('survey_id', 'id'));
    if (array_key_exists('status_id', $params)) {
        $status_id = $params['status_id'];
    } else {
        $status_id = null;
    }
    $surveyID = empty($params['survey_id']) ? $params['id'] : $params['survey_id'];
    require_once 'CRM/Campaign/BAO/Survey.php';
    $survey = new CRM_Campaign_BAO_Survey();
    $voters = $survey->getSurveyVoterInfo($surveyID);
    require_once 'CRM/Contact/BAO/Contact.php';
    foreach ($voters as $key => $voterArray) {
        $voters[$key]['voter_name'] = CRM_Contact_BAO_Contact::displayName($voterArray['voter_id']);
    }
    return civicrm_api3_create_success($voters, $params);
}
/**
 * Create a new Action Schedule
 *
 * @param array $params
 *
 * @return array
 *
 * {@getfields action_schedule_create}
 */
function civicrm_api3_action_schedule_create($params)
{
    if (empty($params['id'])) {
        // an update does not require any mandatory parameters
        civicrm_api3_verify_one_mandatory($params, NULL, array('title', 'mapping_id', 'entity_status', 'entity_value'));
    }
    $ids = array();
    if (isset($params['id']) && !CRM_Utils_Rule::integer($params['id'])) {
        return civicrm_api3_create_error('Invalid value for ID');
    }
    if (!array_key_exists('name', $params) && !array_key_exists('id', $params)) {
        $params['name'] = CRM_Utils_String::munge($params['title']);
    }
    $actionSchedule = new CRM_Core_BAO_ActionSchedule();
    $actionSchedule = CRM_Core_BAO_ActionSchedule::add($params, $ids);
    $actSchedule = array();
    _civicrm_api3_object_to_array($actionSchedule, $actSchedule[$actionSchedule->id]);
    return civicrm_api3_create_success($actSchedule, $params, 'action_schedule', 'create', $actionSchedule);
}
/**
 * Get the list of signatories.
 *
 * @deprecated - api currently not supported
 *
 * @param array $params
 *   input parameters.
 *
 * @return array
 */
function civicrm_api3_survey_respondant_get(&$params)
{
    civicrm_api3_verify_one_mandatory($params, NULL, array('survey_id', 'id'));
    if (array_key_exists('survey_id', $params)) {
        $surveyID = $params['survey_id'];
    } else {
        $surveyID = $params['id'];
    }
    $interviewerID = NULL;
    if (array_key_exists('interviewer_id', $params)) {
        $interviewerID = $params['interviewer_id'];
    }
    $statusIds = array();
    if (array_key_exists('status_id', $params)) {
        $statusIds = explode(',', $params['status_id']);
    }
    $respondants = CRM_Campaign_BAO_Survey::getSurveyActivities($surveyID, $interviewerID, $statusIds);
    return civicrm_api3_create_success($respondants, $params, 'SurveyRespondant', 'get');
}
/**
 *
 * @param <type> $params
 *
 * @return <type>
 * @todo EM 7 Jan 2011 - believe this should be deleted
 * @deprecated
 */
function civicrm_api3_entity_tag_display($params)
{
    civicrm_api3_verify_one_mandatory($params, NULL, array('entity_id', 'contact_id'));
    $entityID = NULL;
    $entityTable = 'civicrm_contact';
    if (!($entityID = CRM_Utils_Array::value('entity_id', $params))) {
        $entityID = CRM_Utils_Array::value('contact_id', $params);
    }
    if (CRM_Utils_Array::value('entity_table', $params)) {
        $entityTable = $params['entity_table'];
    }
    require_once 'CRM/Core/BAO/EntityTag.php';
    $values = CRM_Core_BAO_EntityTag::getTag($entityID, $entityTable);
    $result = array();
    $tags = CRM_Core_PseudoConstant::tag();
    foreach ($values as $v) {
        $result[] = $tags[$v];
    }
    return implode(',', $result);
}
Example #11
0
/**
 * Create or update a saved search.
 *
 * @param array $params
 *   Associative array of property name-value pairs to insert in new saved search.
 * @example SavedSearch/Create.php Std create example.
 * @return array api result array
 *   {@getfields saved_search_create}
 * @access public
 */
function civicrm_api3_saved_search_create($params)
{
    civicrm_api3_verify_one_mandatory($params, NULL, array('form_values', 'where_clause'));
    // The create function of the dao expects a 'formValues' that is
    // not serialized. The get function returns form_values, that is
    // serialized.
    // So for the create API, I guess it should work for serialized and
    // unserialized form_values.
    if (isset($params["form_values"])) {
        if (is_array($params["form_values"])) {
            $params["formValues"] = $params["form_values"];
        } else {
            // Assume that form_values is serialized.
            $params["formValues"] = unserialize($params["form_values"]);
        }
    }
    $result = _civicrm_api3_basic_create(_civicrm_api3_get_BAO(__FUNCTION__), $params);
    _civicrm_api3_saved_search_result_cleanup($result);
    return $result;
}
/**
 * Defines 'uf field' within a group.
 *
 * @param $groupId int Valid uf_group id
 *
 * @param $params  array  Associative array of property name/value pairs to create new uf field.
 *
 * @return Newly created $ufFieldArray array
 *
 * @access public
 * {@getfields UFField_create}
 * @example UFFieldCreate.php
 */
function civicrm_api3_uf_field_create($params)
{
    civicrm_api3_verify_one_mandatory($params, NULL, array('field_name', 'uf_group_id'));
    $groupId = CRM_Utils_Array::value('uf_group_id', $params);
    if ((int) $groupId < 1) {
        return civicrm_api3_create_error('Params must be a field_name-carrying array and a positive integer.');
    }
    $field_type = CRM_Utils_Array::value('field_type', $params);
    $field_name = CRM_Utils_Array::value('field_name', $params);
    $location_type_id = CRM_Utils_Array::value('location_type_id', $params);
    $phone_type = CRM_Utils_Array::value('phone_type', $params);
    $params['field_name'] = array($field_type, $field_name, $location_type_id, $phone_type);
    if (!CRM_Utils_Array::value('group_id', $params)) {
        $params['group_id'] = $groupId;
    }
    $ids = array();
    $ids['uf_group'] = $groupId;
    $fieldId = CRM_Utils_Array::value('id', $params);
    if (!empty($fieldId)) {
        $UFField = new CRM_core_BAO_UFField();
        $UFField->id = $fieldId;
        if ($UFField->find(TRUE)) {
            $ids['uf_group'] = $UFField->uf_group_id;
            if (!CRM_Utils_Array::value('group_id', $params)) {
                // this copied here from previous api function - not sure if required
                $params['group_id'] = $UFField->uf_group_id;
            }
        } else {
            return civicrm_api3_create_error("there is no field for this fieldId");
        }
        $ids['uf_field'] = $fieldId;
    }
    if (CRM_Core_BAO_UFField::duplicateField($params, $ids)) {
        return civicrm_api3_create_error("The field was not added. It already exists in this profile.");
    }
    $ufField = CRM_Core_BAO_UFField::add($params, $ids);
    $fieldsType = CRM_Core_BAO_UFGroup::calculateGroupType($groupId, TRUE);
    CRM_Core_BAO_UFGroup::updateGroupTypes($groupId, $fieldsType);
    _civicrm_api3_object_to_array($ufField, $ufFieldArray[$ufField->id]);
    return civicrm_api3_create_success($ufFieldArray, $params);
}
Example #13
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);
}
Example #14
0
/**
 * Create or update a LocBlock.
 *
 * @param array $params
 *   Name/value pairs to insert in new 'LocBlock'.
 *
 * @return array
 *   API result array.
 *
 * @throws \API_Exception
 */
function civicrm_api3_loc_block_create($params)
{
    $entities = array();
    $any_mandatory = array('address', 'address_id', 'phone', 'phone_id', 'im', 'im_id', 'email', 'email_id');
    civicrm_api3_verify_one_mandatory($params, NULL, $any_mandatory);
    // Call the appropriate api to create entities if any are passed in the params.
    // This is basically chaining but in reverse - we create the sub-entities first
    // because chaining does not work in reverse, or with keys like 'email_2'.
    $items = array('address', 'email', 'phone', 'im');
    foreach ($items as $item) {
        foreach (array('', '_2') as $suf) {
            $key = $item . $suf;
            if (!empty($params[$key]) && is_array($params[$key])) {
                $info = $params[$key];
                // If all we get is an id don't bother calling the api.
                if (count($info) == 1 && !empty($info['id'])) {
                    $params[$key . '_id'] = $info['id'];
                } else {
                    $info['contact_id'] = CRM_Utils_Array::value('contact_id', $info, 'null');
                    $result = civicrm_api3($item, 'create', $info);
                    $entities[$key] = $result['values'][$result['id']];
                    $params[$key . '_id'] = $result['id'];
                }
            }
        }
    }
    $dao = new CRM_Core_DAO_LocBlock();
    $dao->copyValues($params);
    $dao->save();
    if (!empty($dao->id)) {
        $values = array($dao->id => $entities);
        _civicrm_api3_object_to_array($dao, $values[$dao->id]);
        return civicrm_api3_create_success($values, $params, 'LocBlock', 'create', $dao);
    }
    throw new API_Exception('Unable to create LocBlock. Please check your params.');
}
Example #15
0
/**
 * Cancel a recurring contribution of existing ContributionRecur given its id.
 *
 * @param array $params
 *   Array containing id of the recurring contribution.
 *
 * @return bool
 *   returns true is successfully cancelled
 */
function civicrm_api3_contribution_recur_cancel($params)
{
    civicrm_api3_verify_one_mandatory($params, NULL, array('id'));
    return CRM_Contribute_BAO_ContributionRecur::cancelRecurContribution($params['id'], CRM_Core_DAO::$_nullObject) ? civicrm_api3_create_success() : civicrm_api3_create_error(ts('Error while cancelling recurring contribution'));
}
Example #16
0
/**
 * Complete an existing (pending) transaction.
 *
 * This will update related entities (participant, membership, pledge etc)
 * and take any complete actions from the contribution page (e.g. send receipt).
 *
 * @todo - most of this should live in the BAO layer but as we want it to be an addition
 * to 4.3 which is already stable we should add it to the api layer & re-factor into the BAO layer later
 *
 * @param array $params
 *   Input parameters.
 *
 * @throws API_Exception
 *   Api result array.
 */
function civicrm_api3_contribution_repeattransaction(&$params)
{
    $input = $ids = array();
    civicrm_api3_verify_one_mandatory($params, NULL, array('contribution_recur_id', 'original_contribution_id'));
    if (empty($params['original_contribution_id'])) {
        $params['original_contribution_id'] = civicrm_api3('contribution', 'getvalue', array('return' => 'id', 'contribution_recur_id' => $params['contribution_recur_id'], 'options' => array('limit' => 1, 'sort' => 'id DESC')));
    }
    $contribution = new CRM_Contribute_BAO_Contribution();
    $contribution->id = $params['original_contribution_id'];
    if (!$contribution->find(TRUE)) {
        throw new API_Exception('A valid original contribution ID is required', 'invalid_data');
    }
    $original_contribution = clone $contribution;
    try {
        if (!$contribution->loadRelatedObjects($input, $ids, TRUE)) {
            throw new API_Exception('failed to load related objects');
        }
        unset($contribution->id, $contribution->receive_date, $contribution->invoice_id);
        $contribution->receive_date = $params['receive_date'];
        $passThroughParams = array('trxn_id', 'total_amount', 'campaign_id', 'fee_amount', 'financial_type_id', 'contribution_status_id');
        $input = array_intersect_key($params, array_fill_keys($passThroughParams, NULL));
        $params = _ipn_process_transaction($params, $contribution, $input, $ids, $original_contribution);
    } catch (Exception $e) {
        throw new API_Exception('failed to load related objects' . $e->getMessage() . "\n" . $e->getTraceAsString());
    }
}
Example #17
0
/**
 * Creates or updates an Dashlet.
 *
 * @param array $params
 *
 * @return array
 *   Array containing 'is_error' to denote success or failure and details of the created activity
 */
function civicrm_api3_dashboard_create($params)
{
    civicrm_api3_verify_one_mandatory($params, NULL, array('name', 'label', 'url', 'fullscreen_url'));
    return _civicrm_api3_basic_create(_civicrm_api3_get_BAO(__FUNCTION__), $params, 'Dashboard');
}
Example #18
0
/**
 * Create navigation item.
 *
 * @param array $params
 *   Array of name/value pairs.
 *
 * @return array
 *   API result array.
 */
function civicrm_api3_navigation_create($params)
{
    civicrm_api3_verify_one_mandatory($params, NULL, array('name', 'label'));
    return _civicrm_api3_basic_create(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}
Example #19
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);
    }
}
Example #20
0
/**
 * Create an Attachment.
 *
 * @param array $params
 *
 * @return array
 * @throws API_Exception validation errors
 * @see Civi\API\Subscriber\DynamicFKAuthorization
 */
function civicrm_api3_attachment_create($params)
{
    if (empty($params['id'])) {
        // When creating we need either entity_table or field_name
        civicrm_api3_verify_one_mandatory($params, NULL, array('entity_table', 'field_name'));
    }
    $config = CRM_Core_Config::singleton();
    list($id, $file, $entityFile, $name, $content, $moveFile, $isTrusted, $returnContent) = _civicrm_api3_attachment_parse_params($params);
    $fileDao = new CRM_Core_BAO_File();
    $entityFileDao = new CRM_Core_DAO_EntityFile();
    if ($id) {
        $fileDao->id = $id;
        if (!$fileDao->find(TRUE)) {
            throw new API_Exception("Invalid ID");
        }
        $entityFileDao->file_id = $id;
        if (!$entityFileDao->find(TRUE)) {
            throw new API_Exception("Cannot modify orphaned file");
        }
    }
    if (!$id && !is_string($content) && !is_string($moveFile)) {
        throw new API_Exception("Mandatory key(s) missing from params array: 'id' or 'content' or 'options.move-file'");
    }
    if (!$isTrusted && $moveFile) {
        throw new API_Exception("options.move-file is only supported on secure calls");
    }
    if (is_string($content) && is_string($moveFile)) {
        throw new API_Exception("'content' and 'options.move-file' are mutually exclusive");
    }
    if ($id && !$isTrusted && isset($file['upload_date']) && $file['upload_date'] != CRM_Utils_Date::isoToMysql($fileDao->upload_date)) {
        throw new API_Exception("Cannot modify upload_date" . var_export(array($file['upload_date'], $fileDao->upload_date, CRM_Utils_Date::isoToMysql($fileDao->upload_date)), TRUE));
    }
    if ($id && $name && $name != CRM_Utils_File::cleanFileName($fileDao->uri)) {
        throw new API_Exception("Cannot modify name");
    }
    $fileDao->copyValues($file);
    if (!$id) {
        $fileDao->uri = CRM_Utils_File::makeFileName($name);
    }
    $fileDao->save();
    $entityFileDao->copyValues($entityFile);
    $entityFileDao->file_id = $fileDao->id;
    $entityFileDao->save();
    $path = $config->customFileUploadDir . DIRECTORY_SEPARATOR . $fileDao->uri;
    if (is_string($content)) {
        file_put_contents($path, $content);
    } elseif (is_string($moveFile)) {
        // CRM-17432 Do not use rename() since it will break file permissions.
        // Also avoid move_uplaoded_file() because the API can use options.move-file.
        copy($moveFile, $path);
        unlink($moveFile);
    }
    // Save custom field to entity
    if (!$id && empty($params['entity_table']) && isset($params['field_name'])) {
        civicrm_api3('custom_value', 'create', array('entity_id' => $params['entity_id'], $params['field_name'] => $fileDao->id));
    }
    $result = array($fileDao->id => _civicrm_api3_attachment_format_result($fileDao, $entityFileDao, $returnContent, $isTrusted));
    return civicrm_api3_create_success($result, $params, 'Attachment', 'create');
}
Example #21
0
File: File.php Project: kidaa30/yes
/**
 * Get a File.
 *
 * @param array $params
 *   Array per getfields metadata.
 *
 * @return array
 *   Array of all found file object property values.
 */
function civicrm_api3_file_get($params)
{
    civicrm_api3_verify_one_mandatory($params);
    return _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}
Example #22
0
 function testVerifyOneMandatoryOneSet()
 {
     _civicrm_api3_initialize(TRUE);
     $params = array('version' => 3, 'entity_table' => 'civicrm_contact', 'note' => 'note', 'contact_id' => $this->_contactID, 'modified_date' => '2011-01-31', 'subject' => NULL);
     try {
         civicrm_api3_verify_one_mandatory($params, NULL, array('note', 'subject'));
     } catch (Exception $expected) {
         $this->fail('Exception raised when it shouldn\'t have been  in line ' . __LINE__);
     }
 }
/**
 * 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);
}
function _civicrm_api3_contact_check_params(&$params, $dupeCheck = true, $dupeErrorArray = false, $obsoletevalue = true, $dedupeRuleGroupID = null)
{
    switch (strtolower(CRM_Utils_Array::value('contact_type', $params))) {
        case 'household':
            civicrm_api3_verify_mandatory($params, null, array('household_name'));
            break;
        case 'organization':
            civicrm_api3_verify_mandatory($params, null, array('organization_name'));
            break;
        case 'individual':
            civicrm_api3_verify_one_mandatory($params, null, array('first_name', 'last_name', 'email', 'display_name'));
            break;
    }
    if (CRM_Utils_Array::value('contact_sub_type', $params) && CRM_Utils_Array::value('contact_type', $params)) {
        if (!CRM_Contact_BAO_ContactType::isExtendsContactType($params['contact_sub_type'], $params['contact_type'])) {
            return civicrm_api3_create_error("Invalid or Mismatched Contact SubType: " . implode(', ', (array) $params['contact_sub_type']));
        }
    }
    if ($dupeCheck) {
        // check for record already existing
        require_once 'CRM/Dedupe/Finder.php';
        $dedupeParams = CRM_Dedupe_Finder::formatParams($params, $params['contact_type']);
        // CRM-6431
        // setting 'check_permission' here means that the dedupe checking will be carried out even if the
        // person does not have permission to carry out de-dupes
        // this is similar to the front end form
        if (isset($params['check_permission'])) {
            $dedupeParams['check_permission'] = $params['check_permission'];
        }
        $ids = implode(',', CRM_Dedupe_Finder::dupesByParams($dedupeParams, $params['contact_type'], 'Strict', array()));
        if ($ids != NULL) {
            throw new Exception("Found matching contacts: {$ids}");
        }
    }
    //check for organisations with same name
    if (CRM_Utils_Array::value('current_employer', $params)) {
        $organizationParams = array();
        $organizationParams['organization_name'] = $params['current_employer'];
        require_once 'CRM/Dedupe/Finder.php';
        $dedupParams = CRM_Dedupe_Finder::formatParams($organizationParams, 'Organization');
        $dedupParams['check_permission'] = FALSE;
        $dupeIds = CRM_Dedupe_Finder::dupesByParams($dedupParams, 'Organization', 'Fuzzy');
        // check for mismatch employer name and id
        if (CRM_Utils_Array::value('employer_id', $params) && !in_array($params['employer_id'], $dupeIds)) {
            return civicrm_api3_create_error('Employer name and Employer id Mismatch');
        }
        // show error if multiple organisation with same name exist
        if (!CRM_Utils_Array::value('employer_id', $params) && count($dupeIds) > 1) {
            return civicrm_api3_create_error('Found more than one Organisation with same Name.');
        }
    }
    return NULL;
}
Example #25
0
/**
 * Check parameters passed in.
 *
 * This function is on it's way out.
 *
 * @param array $params
 * @param bool $dupeCheck
 *
 * @return null
 * @throws API_Exception
 * @throws CiviCRM_API3_Exception
 */
function _civicrm_api3_contact_check_params(&$params, $dupeCheck)
{
    switch (strtolower(CRM_Utils_Array::value('contact_type', $params))) {
        case 'household':
            civicrm_api3_verify_mandatory($params, NULL, array('household_name'));
            break;
        case 'organization':
            civicrm_api3_verify_mandatory($params, NULL, array('organization_name'));
            break;
        case 'individual':
            civicrm_api3_verify_one_mandatory($params, NULL, array('first_name', 'last_name', 'email', 'display_name'));
            break;
    }
    // Fixme: This really needs to be handled at a lower level. @See CRM-13123
    if (isset($params['preferred_communication_method'])) {
        $params['preferred_communication_method'] = CRM_Utils_Array::implodePadded($params['preferred_communication_method']);
    }
    if (!empty($params['contact_sub_type']) && !empty($params['contact_type'])) {
        if (!CRM_Contact_BAO_ContactType::isExtendsContactType($params['contact_sub_type'], $params['contact_type'])) {
            throw new API_Exception("Invalid or Mismatched Contact Subtype: " . implode(', ', (array) $params['contact_sub_type']));
        }
    }
    if ($dupeCheck) {
        // check for record already existing
        $dedupeParams = CRM_Dedupe_Finder::formatParams($params, $params['contact_type']);
        // CRM-6431
        // setting 'check_permission' here means that the dedupe checking will be carried out even if the
        // person does not have permission to carry out de-dupes
        // this is similar to the front end form
        if (isset($params['check_permission'])) {
            $dedupeParams['check_permission'] = $params['check_permission'];
        }
        $ids = CRM_Dedupe_Finder::dupesByParams($dedupeParams, $params['contact_type'], 'Unsupervised', array());
        if (count($ids) > 0) {
            throw new API_Exception("Found matching contacts: " . implode(',', $ids), "duplicate", array("ids" => $ids));
        }
    }
    // The BAO no longer supports the legacy param "current_employer" so here is a shim for api backward-compatability
    if (!empty($params['current_employer'])) {
        $organizationParams = array('organization_name' => $params['current_employer']);
        $dedupParams = CRM_Dedupe_Finder::formatParams($organizationParams, 'Organization');
        $dedupParams['check_permission'] = FALSE;
        $dupeIds = CRM_Dedupe_Finder::dupesByParams($dedupParams, 'Organization', 'Supervised');
        // check for mismatch employer name and id
        if (!empty($params['employer_id']) && !in_array($params['employer_id'], $dupeIds)) {
            throw new API_Exception('Employer name and Employer id Mismatch');
        }
        // show error if multiple organisation with same name exist
        if (empty($params['employer_id']) && count($dupeIds) > 1) {
            throw new API_Exception('Found more than one Organisation with same Name.');
        }
        if ($dupeIds) {
            $params['employer_id'] = $dupeIds[0];
        } else {
            $result = civicrm_api3('Contact', 'create', array('organization_name' => $params['current_employer'], 'contact_type' => 'Organization'));
            $params['employer_id'] = $result['id'];
        }
    }
    return NULL;
}
/**
 * Retrieve rows from a report template.
 *
 * @param array $params
 *   Input parameters.
 *
 * @return array
 *   API result array
 */
function civicrm_api3_report_template_getrows($params)
{
    civicrm_api3_verify_one_mandatory($params, NULL, array('report_id', 'instance_id'));
    list($rows, $instance, $metadata) = _civicrm_api3_report_template_getrows($params);
    return civicrm_api3_create_success($rows, $params, 'ReportTemplate', 'getrows', CRM_Core_DAO::$_nullObject, $metadata);
}
/**
 * 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);
    }
}