コード例 #1
0
ファイル: Entity.php プロジェクト: hguru/224Civi
/**
 *  returns the list of all the entities that you can manipulate via the api. The entity of this API call is the entity, that isn't a real civicrm entity as in something stored in the DB, but an abstract meta object. My head is going to explode. In a meta way.
 */
function civicrm_api3_entity_get($params)
{
    civicrm_api3_verify_mandatory($params);
    $entities = array();
    $include_dirs = array_unique(explode(PATH_SEPARATOR, get_include_path()));
    #$include_dirs = array(dirname(__FILE__). '/../../');
    foreach ($include_dirs as $include_dir) {
        $api_dir = implode(DIRECTORY_SEPARATOR, array($include_dir, 'api', 'v3'));
        if (!is_dir($api_dir)) {
            continue;
        }
        $iterator = new DirectoryIterator($api_dir);
        foreach ($iterator as $fileinfo) {
            $file = $fileinfo->getFilename();
            // Check for entities with a master file ("api/v3/MyEntity.php")
            $parts = explode(".", $file);
            if (end($parts) == "php" && $file != "utils.php" && !preg_match('/Tests?.php$/', $file)) {
                // without the ".php"
                $entities[] = substr($file, 0, -4);
            }
            // Check for entities with standalone action files ("api/v3/MyEntity/MyAction.php")
            $action_dir = $api_dir . DIRECTORY_SEPARATOR . $file;
            if (preg_match('/^[A-Z][A-Za-z0-9]*$/', $file) && is_dir($action_dir)) {
                if (count(glob("{$action_dir}/[A-Z]*.php")) > 0) {
                    $entities[] = $file;
                }
            }
        }
    }
    $entities = array_diff($entities, array('Generic'));
    $entities = array_unique($entities);
    sort($entities);
    return civicrm_api3_create_success($entities);
}
コード例 #2
0
/**
 * Get available api actions.
 *
 * @param array $apiRequest
 *
 * @return array
 * @throws API_Exception
 */
function civicrm_api3_generic_getActions($apiRequest)
{
    civicrm_api3_verify_mandatory($apiRequest, NULL, array('entity'));
    $mfp = \Civi::service('magic_function_provider');
    $actions = $mfp->getActionNames($apiRequest['version'], $apiRequest['entity']);
    return civicrm_api3_create_success($actions, $apiRequest['params'], $apiRequest['entity'], 'getactions');
}
コード例 #3
0
/**
 * @param $apiRequest
 *
 * @return array
 * @throws API_Exception
 */
function civicrm_api3_generic_getActions($apiRequest)
{
    civicrm_api3_verify_mandatory($apiRequest, NULL, array('entity'));
    $mfp = \Civi\Core\Container::singleton()->get('magic_function_provider');
    $actions = $mfp->getActionNames($apiRequest['version'], $apiRequest['entity']);
    return civicrm_api3_create_success($actions);
}
コード例 #4
0
/**
 * Update an existing membership status.
 *
 * This api is used for updating an existing membership status.
 * Required parameters: id of a membership status
 *
 * @param array $params
 *   Array of name/value property values of civicrm_membership_status.
 *
 * @deprecated - should just use create
 *
 * @return array
 *   Array of updated membership status property values
 */
function civicrm_api3_membership_status_update($params)
{
    civicrm_api3_verify_mandatory($params, NULL, array('id'));
    //don't allow duplicate names.
    $name = CRM_Utils_Array::value('name', $params);
    if ($name) {
        $status = new CRM_Member_DAO_MembershipStatus();
        $status->name = $params['name'];
        if ($status->find(TRUE) && $status->id != $params['id']) {
            return civicrm_api3_create_error(ts('A membership status with this name already exists.'));
        }
    }
    $membershipStatusBAO = new CRM_Member_BAO_MembershipStatus();
    $membershipStatusBAO->id = $params['id'];
    if ($membershipStatusBAO->find(TRUE)) {
        $fields = $membershipStatusBAO->fields();
        foreach ($fields as $name => $field) {
            if (array_key_exists($name, $params)) {
                $membershipStatusBAO->{$name} = $params[$name];
            }
        }
        $membershipStatusBAO->save();
    }
    $membershipStatus = array();
    _civicrm_api3_object_to_array(clone $membershipStatusBAO, $membershipStatus);
    $membershipStatus['is_error'] = 0;
    return $membershipStatus;
}
コード例 #5
0
/**
 * Function to retrieve case types
 *
 * @param $params
 *
 * @return array $caseTypes case types keyed by id
 * @access public
 */
function civicrm_api3_case_type_get($params)
{
    civicrm_api3_verify_mandatory($params);
    $caseTypes = _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params);
    // format case type, to fetch xml definition
    return _civicrm_api3_case_type_get_formatResult($caseTypes);
}
コード例 #6
0
/**
 * params must contain at least id=xx & {one of the fields from getfields}=value
 */
function civicrm_api3_generic_setValue($apiRequest)
{
    $entity = $apiRequest['entity'];
    $params = $apiRequest['params'];
    // we can't use _spec, doesn't work with generic
    civicrm_api3_verify_mandatory($params, NULL, array('id', 'field', 'value'));
    $id = $params['id'];
    if (!is_numeric($id)) {
        return civicrm_api3_create_error(ts('Please enter a number'), array('error_code' => 'NaN', 'field' => "id"));
    }
    $field = CRM_Utils_String::munge($params['field']);
    $value = $params['value'];
    $fields = civicrm_api($entity, 'getFields', array("version" => 3, "sequential"));
    // getfields error, shouldn't happen.
    if ($fields['is_error']) {
        return $fields;
    }
    $fields = $fields['values'];
    if (!array_key_exists($field, $fields)) {
        return civicrm_api3_create_error("Param 'field' ({$field}) is invalid. must be an existing field", array("error_code" => "invalid_field", "fields" => array_keys($fields)));
    }
    $def = $fields[$field];
    if (array_key_exists('required', $def) && empty($value)) {
        return civicrm_api3_create_error(ts("This can't be empty, please provide a value"), array("error_code" => "required", "field" => $field));
    }
    switch ($def['type']) {
        case 1:
            //int
            if (!is_numeric($value)) {
                return civicrm_api3_create_error("Param '{$field}' must be a number", array('error_code' => 'NaN'));
            }
        case 2:
            //string
            require_once "CRM/Utils/Rule.php";
            if (!CRM_Utils_Rule::xssString($value)) {
                return civicrm_api3_create_error(ts('Illegal characters in input (potential scripting attack)'), array('error_code' => 'XSS'));
            }
            if (array_key_exists('maxlength', $def)) {
                $value = substr($value, 0, $def['maxlength']);
            }
            break;
        case 16:
            //boolean
            $value = (bool) $value;
            break;
        case 4:
            //date
        //date
        default:
            return civicrm_api3_create_error("Param '{$field}' is of a type not managed yet. Join the API team and help us implement it", array('error_code' => 'NOT_IMPLEMENTED'));
    }
    if (CRM_Core_DAO::setFieldValue(_civicrm_api3_get_DAO($entity), $id, $field, $value)) {
        $entity = array('id' => $id, $field => $value);
        CRM_Utils_Hook::post('edit', $entity, $id, $entity);
        return civicrm_api3_create_success($entity);
    } else {
        return civicrm_api3_create_error("error assigning {$field}={$value} for {$entity} (id={$id})");
    }
}
コード例 #7
0
/**
 * Handle a queue event.
 *
 * @param array $params
 *   Array of property.
 *
 * @throws Exception
 * @return array
 *   api result array
 */
function civicrm_api3_mailing_event_queue_create($params)
{
    if (!array_key_exists('id', $params) && !array_key_exists('email_id', $params) && !array_key_exists('phone_id', $params)) {
        throw new API_Exception("Mandatory key missing from params array: id, email_id, or phone_id field is required");
    }
    civicrm_api3_verify_mandatory($params, 'CRM_Mailing_DAO_MailingJob', array('job_id', 'contact_id'), FALSE);
    return _civicrm_api3_basic_create('CRM_Mailing_Event_BAO_Queue', $params);
}
コード例 #8
0
/**
 * API to Create or update a Membership Type
 *
 * @param   array  $params  an associative array of name/value property values of civicrm_membership_type
 *
 * @return array $result newly created or updated membership type property values.
 * @access public
 * {getfields MembershipType_get}
 */
function civicrm_api3_membership_type_create($params)
{
    $values = $params;
    civicrm_api3_verify_mandatory($values, 'CRM_Member_DAO_MembershipType');
    $ids['membershipType'] = CRM_Utils_Array::value('id', $values);
    $ids['memberOfContact'] = CRM_Utils_Array::value('member_of_contact_id', $values);
    $ids['contributionType'] = CRM_Utils_Array::value('contribution_type_id', $values);
    require_once 'CRM/Member/BAO/MembershipType.php';
    $membershipTypeBAO = CRM_Member_BAO_MembershipType::add($values, $ids);
    $membershipType = array();
    _civicrm_api3_object_to_array($membershipTypeBAO, $membershipType[$membershipTypeBAO->id]);
    CRM_Member_PseudoConstant::membershipType(NULL, TRUE);
    return civicrm_api3_create_success($membershipType, $params, 'membership_type', 'create', $membershipTypeBAO);
}
コード例 #9
0
ファイル: CaseType.php プロジェクト: kidaa30/yes
/**
 * Create or update case type.
 *
 * @param array $params
 *   Input parameters.
 *
 * @throws API_Exception
 * @return array
 *   API result array
 */
function civicrm_api3_case_type_create($params)
{
    civicrm_api3_verify_mandatory($params, _civicrm_api3_get_DAO(__FUNCTION__));
    // Computed properties.
    unset($params['is_forkable']);
    unset($params['is_forked']);
    if (!array_key_exists('is_active', $params) && empty($params['id'])) {
        $params['is_active'] = TRUE;
    }
    // This is an existing case-type.
    if (!empty($params['id']) && !CRM_Case_BAO_CaseType::isForked($params['id']) && !CRM_Case_BAO_CaseType::isForkable($params['id'])) {
        unset($params['definition']);
    }
    $result = _civicrm_api3_basic_create(_civicrm_api3_get_BAO(__FUNCTION__), $params, 'CaseType');
    return _civicrm_api3_case_type_get_formatResult($result);
}
コード例 #10
0
ファイル: Website.php プロジェクト: kcristiano/civicrm-core
/**
 * Deletes an existing Website.
 *
 * @todo convert to using Basic delete - BAO function non standard
 *
 * @param array $params
 *
 * @return array
 *   API result array
 * @throws \API_Exception
 */
function civicrm_api3_website_delete($params)
{
    //DO NOT USE THIS FUNCTION AS THE BASIS FOR A NEW API http://wiki.civicrm.org/confluence/display/CRM/API+Architecture+Standards
    civicrm_api3_verify_mandatory($params, NULL, array('id'));
    _civicrm_api3_check_edit_permissions('CRM_Core_BAO_Website', array('id' => $params['id']));
    $websiteDAO = new CRM_Core_DAO_Website();
    $websiteDAO->id = $params['id'];
    if ($websiteDAO->find()) {
        while ($websiteDAO->fetch()) {
            $websiteDAO->delete();
            return civicrm_api3_create_success(1, $params, 'Website', 'delete');
        }
    } else {
        throw new API_Exception('Could not delete Website with id ' . $params['id']);
    }
}
コード例 #11
0
 /**
  * @param \Civi\API\Event\PrepareEvent $event
  *   API preparation event.
  *
  * @throws \API_Exception
  */
 public function onApiPrepare(\Civi\API\Event\PrepareEvent $event)
 {
     $apiRequest = $event->getApiRequest();
     if ($apiRequest['version'] > 3) {
         return;
     }
     $apiRequest['fields'] = _civicrm_api3_api_getfields($apiRequest);
     _civicrm_api3_swap_out_aliases($apiRequest, $apiRequest['fields']);
     if (strtolower($apiRequest['action']) != 'getfields') {
         if (empty($apiRequest['params']['id'])) {
             $apiRequest['params'] = array_merge($this->getDefaults($apiRequest['fields']), $apiRequest['params']);
         }
         // Note: If 'id' is set then verify_mandatory will only check 'version'.
         civicrm_api3_verify_mandatory($apiRequest['params'], NULL, $this->getRequired($apiRequest['fields']));
     }
     $event->setApiRequest($apiRequest);
 }
コード例 #12
0
ファイル: Event.php プロジェクト: kcristiano/civicrm-core
/**
 * Create a Event.
 *
 * @param array $params
 *   Input parameters.
 *
 * @return array
 *   API result Array.
 */
function civicrm_api3_event_create($params)
{
    // Required fields for creating an event
    if (empty($params['id']) && empty($params['is_template'])) {
        civicrm_api3_verify_mandatory($params, NULL, array('start_date', 'title', array('event_type_id', 'template_id')));
    } elseif (empty($params['id']) && !empty($params['is_template'])) {
        civicrm_api3_verify_mandatory($params, NULL, array('template_title'));
    }
    // 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');
}
コード例 #13
0
function civicrm_api3_generic_getActions($params)
{
    civicrm_api3_verify_mandatory($params, NULL, array('entity'));
    $r = civicrm_api('Entity', 'Get', array('version' => 3));
    $entity = CRM_Utils_String::munge($params['entity']);
    if (!in_array($entity, $r['values'])) {
        return civicrm_api3_create_error("Entity " . $entity . " invalid. Use api.entity.get to have the list", array('entity' => $r['values']));
    }
    _civicrm_api_loadEntity($entity);
    $functions = get_defined_functions();
    $actions = array();
    $prefix = 'civicrm_api3_' . strtolower($entity) . '_';
    $prefixGeneric = 'civicrm_api3_generic_';
    foreach ($functions['user'] as $fct) {
        if (strpos($fct, $prefix) === 0) {
            $actions[] = substr($fct, strlen($prefix));
        } elseif (strpos($fct, $prefixGeneric) === 0) {
            $actions[] = substr($fct, strlen($prefixGeneric));
        }
    }
    return civicrm_api3_create_success($actions);
}
コード例 #14
0
ファイル: MailingAB.php プロジェクト: nielosz/civicrm-core
/**
 * Send graph detail for A/B tests mail.
 *
 * @param array $params
 *
 * @return array
 * @throws API_Exception
 */
function civicrm_api3_mailing_a_b_graph_stats($params)
{
    civicrm_api3_verify_mandatory($params, 'CRM_Mailing_DAO_MailingAB', array('id'), FALSE);
    $defaults = array('criteria' => 'Open', 'target_date' => CRM_Utils_Time::getTime('YmdHis'), 'split_count' => 6, 'split_count_select' => 1);
    $params = array_merge($defaults, $params);
    $mailingAB = civicrm_api3('MailingAB', 'getsingle', array('id' => $params['id']));
    $graphStats = array();
    $ABFormat = array('A' => 'mailing_id_a', 'B' => 'mailing_id_b');
    foreach ($ABFormat as $name => $column) {
        switch (strtolower($params['criteria'])) {
            case 'open':
                $result = CRM_Mailing_Event_BAO_Opened::getRows($mailingAB['mailing_id_a'], NULL, TRUE, 0, 1, "civicrm_mailing_event_opened.time_stamp ASC");
                $startDate = CRM_Utils_Date::processDate($result[0]['date']);
                $targetDate = CRM_Utils_Date::processDate($params['target_date']);
                $dateDuration = round(round(strtotime($targetDate) - strtotime($startDate)) / $params['split_count']);
                $toDate = strtotime($startDate) + $dateDuration * $params['split_count_select'];
                $toDate = date('YmdHis', $toDate);
                $graphStats[$name] = array($params['split_count_select'] => array('count' => CRM_Mailing_Event_BAO_Opened::getTotalCount($mailingAB[$column], NULL, TRUE, $toDate), 'time' => CRM_Utils_Date::customFormat($toDate)));
                break;
            case 'total unique clicks':
                $result = CRM_Mailing_Event_BAO_TrackableURLOpen::getRows($mailingAB['mailing_id_a'], NULL, TRUE, 0, 1, "civicrm_mailing_event_trackable_url_open.time_stamp ASC");
                $startDate = CRM_Utils_Date::processDate($result[0]['date']);
                $targetDate = CRM_Utils_Date::processDate($params['target_date']);
                $dateDuration = round(abs(strtotime($targetDate) - strtotime($startDate)) / $params['split_count']);
                $toDate = strtotime($startDate) + $dateDuration * $params['split_count_select'];
                $toDate = date('YmdHis', $toDate);
                $graphStats[$name] = array($params['split_count_select'] => array('count' => CRM_Mailing_Event_BAO_TrackableURLOpen::getTotalCount($params['mailing_id'], NULL, FALSE, NULL, $toDate), 'time' => CRM_Utils_Date::customFormat($toDate)));
                break;
            case 'total clicks on a particular link':
                if (empty($params['target_url'])) {
                    throw new API_Exception("Provide url to get stats result for total clicks on a particular link");
                }
                // FIXME: doesn't make sense to get url_id mailing_id_(a|b) while getting start date in mailing_id_a
                $url_id = CRM_Mailing_BAO_TrackableURL::getTrackerURLId($mailingAB[$column], $params['target_url']);
                $result = CRM_Mailing_Event_BAO_TrackableURLOpen::getRows($mailingAB['mailing_id_a'], NULL, FALSE, $url_id, 0, 1, "civicrm_mailing_event_trackable_url_open.time_stamp ASC");
                $startDate = CRM_Utils_Date::processDate($result[0]['date']);
                $targetDate = CRM_Utils_Date::processDate($params['target_date']);
                $dateDuration = round(abs(strtotime($targetDate) - strtotime($startDate)) / $params['split_count']);
                $toDate = strtotime($startDate) + $dateDuration * $params['split_count_select'];
                $toDate = CRM_Utils_Date::processDate($toDate);
                $graphStats[$name] = array($params['split_count_select'] => array('count' => CRM_Mailing_Event_BAO_TrackableURLOpen::getTotalCount($params['mailing_id'], NULL, FALSE, $url_id, $toDate), 'time' => CRM_Utils_Date::customFormat($toDate)));
                break;
        }
    }
    return civicrm_api3_create_success($graphStats);
}
コード例 #15
0
/**
 * Update group contact status.
 *
 * @deprecated - this should be part of create but need to know we aren't missing something
 *
 * @param array $params
 *
 * @return bool
 * @throws \API_Exception
 */
function civicrm_api3_group_contact_update_status($params)
{
    civicrm_api3_verify_mandatory($params, NULL, array('contact_id', 'group_id'));
    CRM_Contact_BAO_GroupContact::addContactsToGroup(array($params['contact_id']), $params['group_id'], CRM_Utils_Array::value('method', $params, 'API'), 'Added', CRM_Utils_Array::value('tracking', $params));
    return TRUE;
}
コード例 #16
0
ファイル: Note.php プロジェクト: hguru/224Civi
/**
 * Get all descendents of given note
 *
 * @param array $params Associative array; only required 'id' parameter is used
 *
 * @return array Nested associative array beginning with direct children of given note.
 */
function &civicrm_api3_note_tree_get($params)
{
    civicrm_api3_verify_mandatory($params, NULL, array('id'));
    if (!is_numeric($params['id'])) {
        return civicrm_api3_create_error(ts("Invalid note ID"));
    }
    if (!isset($params['max_depth'])) {
        $params['max_depth'] = 0;
    }
    if (!isset($params['snippet'])) {
        $params['snippet'] = FALSE;
    }
    $noteTree = CRM_Core_BAO_Note::getNoteTree($params['id'], $params['max_depth'], $params['snippet']);
    return civicrm_api3_create_success($noteTree, $params);
}
コード例 #17
0
 function testVerifyMandatory()
 {
     _civicrm_api3_initialize(TRUE);
     $params = array('entity_table' => 'civicrm_contact', 'note' => '', 'contact_id' => $this->_contactID, 'modified_date' => '2011-01-31', 'subject' => NULL, 'version' => $this->_apiversion);
     try {
         $result = civicrm_api3_verify_mandatory($params, 'CRM_Core_BAO_Note', array('note', 'subject'));
     } catch (Exception $expected) {
         $this->assertEquals('Mandatory key(s) missing from params array: entity_id, note, subject', $expected->getMessage());
         return;
     }
     $this->fail('An expected exception has not been raised.');
 }
コード例 #18
0
ファイル: Mailing.php プロジェクト: rameshrr99/civicrm-core
/**
 * Function which needs to be explained.
 *
 * @param array $params
 *
 * @return array
 * @throws \API_Exception
 */
function civicrm_api3_mailing_stats($params)
{
    civicrm_api3_verify_mandatory($params, 'CRM_Mailing_DAO_MailingJob', array('mailing_id'), FALSE);
    if ($params['date'] == 'now') {
        $params['date'] = date('YmdHis');
    } else {
        $params['date'] = CRM_Utils_Date::processDate($params['date'] . ' ' . $params['date_time']);
    }
    $stats[$params['mailing_id']] = array();
    if (empty($params['job_id'])) {
        $params['job_id'] = NULL;
    }
    foreach (array('Delivered', 'Bounces', 'Unsubscribers', 'Unique Clicks', 'Opened') as $detail) {
        switch ($detail) {
            case 'Delivered':
                $stats[$params['mailing_id']] += array($detail => CRM_Mailing_Event_BAO_Delivered::getTotalCount($params['mailing_id'], $params['job_id'], FALSE, $params['date']));
                break;
            case 'Bounces':
                $stats[$params['mailing_id']] += array($detail => CRM_Mailing_Event_BAO_Bounce::getTotalCount($params['mailing_id'], $params['job_id'], FALSE, $params['date']));
                break;
            case 'Unsubscribers':
                $stats[$params['mailing_id']] += array($detail => CRM_Mailing_Event_BAO_Unsubscribe::getTotalCount($params['mailing_id'], $params['job_id'], FALSE, NULL, $params['date']));
                break;
            case 'Unique Clicks':
                $stats[$params['mailing_id']] += array($detail => CRM_Mailing_Event_BAO_TrackableURLOpen::getTotalCount($params['mailing_id'], $params['job_id'], FALSE, NULL, $params['date']));
                break;
            case 'Opened':
                $stats[$params['mailing_id']] += array($detail => CRM_Mailing_Event_BAO_Opened::getTotalCount($params['mailing_id'], $params['job_id'], FALSE, $params['date']));
                break;
        }
    }
    return civicrm_api3_create_success($stats);
}
コード例 #19
0
/**
 *
 * This method allows to update Email Greetings, Postal Greetings and Addressee for a specific contact type.
 * IMPORTANT: You must first create valid option value before using via admin interface.
 * Check option lists for Email Greetings, Postal Greetings and Addressee
 *
 * @param  array   	  $params (reference ) input parameters
 *                        ct - String - ct=Individual or ct=Household or ct=Organization
 *                        gt - String - gt=email_greeting or gt=postal_greeting or gt=addressee
 *                        id - Integer - greetings option group
 *
 * @return boolean        true if success, else false
 * @static
 * @access public
 *
 */
function civicrm_api3_job_update_greeting($params)
{
    require_once 'CRM/Contact/BAO/Contact/Utils.php';
    civicrm_api3_verify_mandatory($params, NULL, array('ct', 'gt'));
    // fixme - use the wrapper & getfields to do this checking - advertise as an enum
    if (!in_array($params['ct'], array('Individual', 'Household', 'Organization'))) {
        return civicrm_api3_create_error(ts('Invalid contact type (ct) parameter value'));
    }
    if (!in_array($params['gt'], array('email_greeting', 'postal_greeting', 'addressee'))) {
        return civicrm_api3_create_error(ts('Invalid greeting type (gt) parameter value'));
    }
    $result = CRM_Contact_BAO_Contact_Utils::updateGreeting($params);
    if ($result['is_error'] == 0) {
        return civicrm_api3_create_success();
    } else {
        return civicrm_api3_create_error($result['messages']);
    }
}
コード例 #20
0
/**
 * Function to delete activity type
 *
 * @param activityTypeId int   activity type id to delete
 *
 * @return boolen
 *
 * @access public
 *
 * @deprecated - we will introduce OptionValue Delete- plse consider helping with this if not done
 * {@example ActivityTypeDelete.php 0}
 */
function civicrm_api3_activity_type_delete($params)
{
    civicrm_api3_verify_mandatory($params, NULL, array('activity_type_id'));
    $activityTypeId = $params['activity_type_id'];
    require_once 'CRM/Core/BAO/OptionValue.php';
    return CRM_Core_BAO_OptionValue::del($activityTypeId);
}
コード例 #21
0
ファイル: Contact.php プロジェクト: rajeshrhino/civicrm-core
/**
 * Old Contact quick search api.
 *
 * @deprecated
 *
 * @param array $params
 *
 * @return array
 * @throws \API_Exception
 */
function civicrm_api3_contact_getquick($params)
{
    civicrm_api3_verify_mandatory($params, NULL, array('name'));
    $name = CRM_Utils_Type::escape(CRM_Utils_Array::value('name', $params), 'String');
    // get the autocomplete options from settings
    $acpref = explode(CRM_Core_DAO::VALUE_SEPARATOR, CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'contact_autocomplete_options'));
    // get the option values for contact autocomplete
    $acOptions = CRM_Core_OptionGroup::values('contact_autocomplete_options', FALSE, FALSE, FALSE, NULL, 'name');
    $list = array();
    foreach ($acpref as $value) {
        if ($value && !empty($acOptions[$value])) {
            $list[$value] = $acOptions[$value];
        }
    }
    // If we are doing quicksearch by a field other than name, make sure that field is added to results
    if (!empty($params['field_name'])) {
        $field_name = CRM_Utils_String::munge($params['field_name']);
        // Unique name contact_id = id
        if ($field_name == 'contact_id') {
            $field_name = 'id';
        }
        // phone_numeric should be phone
        $searchField = str_replace('_numeric', '', $field_name);
        if (!in_array($searchField, $list)) {
            $list[] = $searchField;
        }
    }
    $select = $actualSelectElements = array('sort_name');
    $where = '';
    $from = array();
    foreach ($list as $value) {
        $suffix = substr($value, 0, 2) . substr($value, -1);
        switch ($value) {
            case 'street_address':
            case 'city':
            case 'postal_code':
                $selectText = $value;
                $value = "address";
                $suffix = 'sts';
            case 'phone':
            case 'email':
                $actualSelectElements[] = $select[] = $value == 'address' ? $selectText : $value;
                if ($value == 'phone') {
                    $actualSelectElements[] = $select[] = 'phone_ext';
                }
                $from[$value] = "LEFT JOIN civicrm_{$value} {$suffix} ON ( cc.id = {$suffix}.contact_id AND {$suffix}.is_primary = 1 ) ";
                break;
            case 'country':
            case 'state_province':
                $select[] = "{$suffix}.name as {$value}";
                $actualSelectElements[] = "{$suffix}.name";
                if (!in_array('address', $from)) {
                    $from['address'] = 'LEFT JOIN civicrm_address sts ON ( cc.id = sts.contact_id AND sts.is_primary = 1) ';
                }
                $from[$value] = " LEFT JOIN civicrm_{$value} {$suffix} ON ( sts.{$value}_id = {$suffix}.id  ) ";
                break;
            default:
                if ($value != 'id') {
                    $suffix = 'cc';
                    if (!empty($params['field_name']) && $params['field_name'] == 'value') {
                        $suffix = CRM_Utils_String::munge(CRM_Utils_Array::value('table_name', $params, 'cc'));
                    }
                    $actualSelectElements[] = $select[] = $suffix . '.' . $value;
                }
                break;
        }
    }
    $config = CRM_Core_Config::singleton();
    $as = $select;
    $select = implode(', ', $select);
    if (!empty($select)) {
        $select = ", {$select}";
    }
    $actualSelectElements = implode(', ', $actualSelectElements);
    $selectAliases = $from;
    unset($selectAliases['address']);
    $selectAliases = implode(', ', array_keys($selectAliases));
    if (!empty($selectAliases)) {
        $selectAliases = ", {$selectAliases}";
    }
    $from = implode(' ', $from);
    $limit = (int) CRM_Utils_Array::value('limit', $params);
    $limit = $limit > 0 ? $limit : CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SEARCH_PREFERENCES_NAME, 'search_autocomplete_count', NULL, 10);
    // add acl clause here
    list($aclFrom, $aclWhere) = CRM_Contact_BAO_Contact_Permission::cacheClause('cc');
    if ($aclWhere) {
        $where .= " AND {$aclWhere} ";
    }
    if (!empty($params['org'])) {
        $where .= " AND contact_type = \"Organization\"";
        // CRM-7157, hack: get current employer details when
        // employee_id is present.
        $currEmpDetails = array();
        if (!empty($params['employee_id'])) {
            if ($currentEmployer = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', (int) $params['employee_id'], 'employer_id')) {
                if ($config->includeWildCardInName) {
                    $strSearch = "%{$name}%";
                } else {
                    $strSearch = "{$name}%";
                }
                // get current employer details
                $dao = CRM_Core_DAO::executeQuery("SELECT cc.id as id, CONCAT_WS( ' :: ', {$actualSelectElements} ) as data, sort_name\n                    FROM civicrm_contact cc {$from} WHERE cc.contact_type = \"Organization\" AND cc.id = {$currentEmployer} AND cc.sort_name LIKE '{$strSearch}'");
                if ($dao->fetch()) {
                    $currEmpDetails = array('id' => $dao->id, 'data' => $dao->data);
                }
            }
        }
    }
    if (!empty($params['contact_sub_type'])) {
        $contactSubType = CRM_Utils_Type::escape($params['contact_sub_type'], 'String');
        $where .= " AND cc.contact_sub_type = '{$contactSubType}'";
    }
    if (!empty($params['contact_type'])) {
        $contactType = CRM_Utils_Type::escape($params['contact_type'], 'String');
        $where .= " AND cc.contact_type LIKE '{$contactType}'";
    }
    // Set default for current_employer or return contact with particular id
    if (!empty($params['id'])) {
        $where .= " AND cc.id = " . (int) $params['id'];
    }
    if (!empty($params['cid'])) {
        $where .= " AND cc.id <> " . (int) $params['cid'];
    }
    // Contact's based of relationhip type
    $relType = NULL;
    if (!empty($params['rel'])) {
        $relation = explode('_', CRM_Utils_Array::value('rel', $params));
        $relType = CRM_Utils_Type::escape($relation[0], 'Integer');
        $rel = CRM_Utils_Type::escape($relation[2], 'String');
    }
    if ($config->includeWildCardInName) {
        $strSearch = "%{$name}%";
    } else {
        $strSearch = "{$name}%";
    }
    $includeEmailFrom = $includeNickName = $exactIncludeNickName = '';
    if ($config->includeNickNameInName) {
        $includeNickName = " OR nick_name LIKE '{$strSearch}'";
        $exactIncludeNickName = " OR nick_name LIKE '{$name}'";
    }
    //CRM-10687
    if (!empty($params['field_name']) && !empty($params['table_name'])) {
        $table_name = CRM_Utils_String::munge($params['table_name']);
        $whereClause = " WHERE ( {$table_name}.{$field_name} LIKE '{$strSearch}') {$where}";
        $exactWhereClause = " WHERE ( {$table_name}.{$field_name} = '{$name}') {$where}";
        // Search by id should be exact
        if ($field_name == 'id' || $field_name == 'external_identifier') {
            $whereClause = $exactWhereClause;
        }
    } else {
        if ($config->includeEmailInName) {
            if (!in_array('email', $list)) {
                $includeEmailFrom = "LEFT JOIN civicrm_email eml ON ( cc.id = eml.contact_id AND eml.is_primary = 1 )";
            }
            $whereClause = " WHERE ( email LIKE '{$strSearch}' OR sort_name LIKE '{$strSearch}' {$includeNickName} ) {$where} ";
            $exactWhereClause = " WHERE ( email LIKE '{$name}' OR sort_name LIKE '{$name}' {$exactIncludeNickName} ) {$where} ";
        } else {
            $whereClause = " WHERE ( sort_name LIKE '{$strSearch}' {$includeNickName} ) {$where} ";
            $exactWhereClause = " WHERE ( sort_name LIKE '{$name}' {$exactIncludeNickName} ) {$where} ";
        }
    }
    $additionalFrom = '';
    if ($relType) {
        $additionalFrom = "\n            INNER JOIN civicrm_relationship_type r ON (\n                r.id = {$relType}\n                AND ( cc.contact_type = r.contact_type_{$rel} OR r.contact_type_{$rel} IS NULL )\n                AND ( cc.contact_sub_type = r.contact_sub_type_{$rel} OR r.contact_sub_type_{$rel} IS NULL )\n            )";
    }
    // check if only CMS users are requested
    if (!empty($params['cmsuser'])) {
        $additionalFrom = "\n      INNER JOIN civicrm_uf_match um ON (um.contact_id=cc.id)\n      ";
    }
    $orderByInner = "";
    $orderByOuter = "ORDER BY exactFirst";
    if ($config->includeOrderByClause) {
        $orderByInner = "ORDER BY sort_name";
        $orderByOuter .= ", sort_name";
    }
    //CRM-5954
    $query = "\n        SELECT DISTINCT(id), data, sort_name {$selectAliases}\n        FROM   (\n            ( SELECT 0 as exactFirst, cc.id as id, CONCAT_WS( ' :: ', {$actualSelectElements} ) as data {$select}\n            FROM   civicrm_contact cc {$from}\n    {$aclFrom}\n    {$additionalFrom} {$includeEmailFrom}\n    {$exactWhereClause}\n    LIMIT 0, {$limit} )\n    UNION\n    ( SELECT 1 as exactFirst, cc.id as id, CONCAT_WS( ' :: ', {$actualSelectElements} ) as data {$select}\n    FROM   civicrm_contact cc {$from}\n    {$aclFrom}\n    {$additionalFrom} {$includeEmailFrom}\n    {$whereClause}\n    {$orderByInner}\n    LIMIT 0, {$limit} )\n) t\n{$orderByOuter}\nLIMIT    0, {$limit}\n    ";
    // send query to hook to be modified if needed
    CRM_Utils_Hook::contactListQuery($query, $name, empty($params['context']) ? NULL : CRM_Utils_Type::escape($params['context'], 'String'), empty($params['id']) ? NULL : $params['id']);
    $dao = CRM_Core_DAO::executeQuery($query);
    $contactList = array();
    $listCurrentEmployer = TRUE;
    while ($dao->fetch()) {
        $t = array('id' => $dao->id);
        foreach ($as as $k) {
            $t[$k] = isset($dao->{$k}) ? $dao->{$k} : '';
        }
        $t['data'] = $dao->data;
        $contactList[] = $t;
        if (!empty($params['org']) && !empty($currEmpDetails) && $dao->id == $currEmpDetails['id']) {
            $listCurrentEmployer = FALSE;
        }
    }
    //return organization name if doesn't exist in db
    if (empty($contactList)) {
        if (!empty($params['org'])) {
            if ($listCurrentEmployer && !empty($currEmpDetails)) {
                $contactList = array(array('data' => $currEmpDetails['data'], 'id' => $currEmpDetails['id']));
            } else {
                $contactList = array(array('data' => $name, 'id' => $name));
            }
        }
    }
    return civicrm_api3_create_success($contactList, $params, 'Contact', 'getquick');
}
コード例 #22
0
/**
 * Returns array of contact_types matching a set of one or more properties.
 *
 * @param array $params
 *   One or more valid property_name=>value pairs.
 *   If $params is set as null, all contact_types will be returned
 *
 * @return array
 *   Array of matching contact_types
 */
function civicrm_api3_contact_type_get($params)
{
    civicrm_api3_verify_mandatory($params);
    return _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}
コード例 #23
0
ファイル: File.php プロジェクト: kidaa30/yes
/**
 * Delete an existing File.
 *
 * @param array $params
 *   Array per getfields metadata.
 *
 * @return array
 *   API result array
 */
function civicrm_api3_file_delete($params)
{
    civicrm_api3_verify_mandatory($params, NULL, array('id'));
    $check = FALSE;
    $entityFileDAO = new CRM_Core_DAO_EntityFile();
    $entityFileDAO->file_id = $params['id'];
    if ($entityFileDAO->find()) {
        $check = $entityFileDAO->delete();
    }
    $fileDAO = new CRM_Core_DAO_File();
    $fileDAO->id = $params['id'];
    if ($fileDAO->find(TRUE)) {
        $check = $fileDAO->delete();
    }
    return $check ? NULL : civicrm_api3_create_error('Error while deleting a file.');
}
コード例 #24
0
/**
 * Handle an open event
 *
 * @param array $params
 *
 * @return array
 */
function civicrm_api3_mailing_event_open($params)
{
    civicrm_api3_verify_mandatory($params, 'CRM_Mailing_Event_DAO_Opened', array('event_queue_id'), FALSE);
    $queue = $params['event_queue_id'];
    $success = CRM_Mailing_Event_BAO_Opened::open($queue);
    if (!$success) {
        return civicrm_api3_create_error('mailing open event failed');
    }
    return civicrm_api3_create_success($params);
}
コード例 #25
0
ファイル: Contact.php プロジェクト: nielosz/civicrm-core
/**
 * 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;
}
コード例 #26
0
/**
 * params must contain at least id=xx & {one of the fields from getfields}=value
 */
function civicrm_api3_generic_setValue($apiRequest)
{
    $entity = $apiRequest['entity'];
    $params = $apiRequest['params'];
    // we can't use _spec, doesn't work with generic
    civicrm_api3_verify_mandatory($params, NULL, array('id', 'field', 'value'));
    $id = $params['id'];
    if (!is_numeric($id)) {
        return civicrm_api3_create_error(ts('Please enter a number'), array('error_code' => 'NaN', 'field' => "id"));
    }
    $field = CRM_Utils_String::munge($params['field']);
    $value = $params['value'];
    $fields = civicrm_api($entity, 'getFields', array('version' => 3, 'action' => 'create', "sequential"));
    // getfields error, shouldn't happen.
    if ($fields['is_error']) {
        return $fields;
    }
    $fields = $fields['values'];
    if (!array_key_exists($field, $fields)) {
        return civicrm_api3_create_error("Param 'field' ({$field}) is invalid. must be an existing field", array("error_code" => "invalid_field", "fields" => array_keys($fields)));
    }
    $def = $fields[$field];
    // Disallow empty values except for the number zero.
    // TODO: create a utility for this since it's needed in many places
    // if (array_key_exists('required', $def) && CRM_Utils_System::isNull($value)) {
    if (array_key_exists('required', $def) && empty($value) && $value !== '0' && $value !== 0) {
        return civicrm_api3_create_error(ts("This can't be empty, please provide a value"), array("error_code" => "required", "field" => $field));
    }
    switch ($def['type']) {
        case CRM_Utils_Type::T_INT:
            if (!is_numeric($value)) {
                return civicrm_api3_create_error("Param '{$field}' must be a number", array('error_code' => 'NaN'));
            }
        case CRM_Utils_Type::T_STRING:
        case CRM_Utils_Type::T_TEXT:
            if (!CRM_Utils_Rule::xssString($value)) {
                return civicrm_api3_create_error(ts('Illegal characters in input (potential scripting attack)'), array('error_code' => 'XSS'));
            }
            if (array_key_exists('maxlength', $def)) {
                $value = substr($value, 0, $def['maxlength']);
            }
            break;
        case CRM_Utils_Type::T_DATE:
            $value = CRM_Utils_Type::escape($value, "Date", false);
            if (!$value) {
                return civicrm_api3_create_error("Param '{$field}' is not a date. format YYYYMMDD or YYYYMMDDHHMMSS");
            }
            break;
        case CRM_Utils_Type::T_BOOLEAN:
            $value = (bool) $value;
            break;
        default:
            return civicrm_api3_create_error("Param '{$field}' is of a type not managed yet (" . $def['type'] . "). Join the API team and help us implement it", array('error_code' => 'NOT_IMPLEMENTED'));
    }
    $dao_name = _civicrm_api3_get_DAO($entity);
    if (CRM_Core_DAO::setFieldValue($dao_name, $id, $field, $value)) {
        $params = array('id' => $id, $field => $value);
        $entityDAO = new $dao_name();
        $entityDAO->copyValues($params);
        CRM_Utils_Hook::post('edit', $entity, $entityDAO->id, $entityDAO);
        return civicrm_api3_create_success($params);
    } else {
        return civicrm_api3_create_error("error assigning {$field}={$value} for {$entity} (id={$id})");
    }
}
コード例 #27
0
ファイル: api.php プロジェクト: archcidburnziso/civicrm-core
/**
 * @param string $entity
 *   type of entities to deal with
 * @param string $action
 *   create, get, delete or some special action name.
 * @param array $params
 *   array to be passed to function
 * @param null $extra
 *
 * @return array|int
 */
function civicrm_api($entity, $action, $params, $extra = NULL)
{
    $apiRequest = array();
    $apiRequest['entity'] = CRM_Utils_String::munge($entity);
    $apiRequest['action'] = CRM_Utils_String::munge($action);
    $apiRequest['version'] = civicrm_get_api_version($params);
    $apiRequest['params'] = $params;
    $apiRequest['extra'] = $extra;
    $apiWrappers = array(CRM_Utils_API_HTMLInputCoder::singleton(), CRM_Utils_API_NullOutputCoder::singleton(), CRM_Utils_API_ReloadOption::singleton(), CRM_Utils_API_MatchOption::singleton());
    CRM_Utils_Hook::apiWrappers($apiWrappers, $apiRequest);
    try {
        require_once 'api/v3/utils.php';
        require_once 'api/Exception.php';
        if (!is_array($params)) {
            throw new API_Exception('Input variable `params` is not an array', 2000);
        }
        _civicrm_api3_initialize();
        $errorScope = CRM_Core_TemporaryErrorScope::useException();
        // look up function, file, is_generic
        $apiRequest += _civicrm_api_resolve($apiRequest);
        if (strtolower($action) == 'create' || strtolower($action) == 'delete' || strtolower($action) == 'submit') {
            $apiRequest['is_transactional'] = 1;
            $transaction = new CRM_Core_Transaction();
        }
        // support multi-lingual requests
        if ($language = CRM_Utils_Array::value('option.language', $params)) {
            _civicrm_api_set_locale($language);
        }
        _civicrm_api3_api_check_permission($apiRequest['entity'], $apiRequest['action'], $apiRequest['params']);
        $fields = _civicrm_api3_api_getfields($apiRequest);
        // we do this before we
        _civicrm_api3_swap_out_aliases($apiRequest, $fields);
        if (strtolower($action) != 'getfields') {
            if (empty($apiRequest['params']['id'])) {
                $apiRequest['params'] = array_merge(_civicrm_api3_getdefaults($apiRequest, $fields), $apiRequest['params']);
            }
            //if 'id' is set then only 'version' will be checked but should still be checked for consistency
            civicrm_api3_verify_mandatory($apiRequest['params'], NULL, _civicrm_api3_getrequired($apiRequest, $fields));
        }
        // For input filtering, process $apiWrappers in forward order
        foreach ($apiWrappers as $apiWrapper) {
            $apiRequest = $apiWrapper->fromApiInput($apiRequest);
        }
        $function = $apiRequest['function'];
        if ($apiRequest['function'] && $apiRequest['is_generic']) {
            // Unlike normal API implementations, generic implementations require explicit
            // knowledge of the entity and action (as well as $params). Bundle up these bits
            // into a convenient data structure.
            $result = $function($apiRequest);
        } elseif ($apiRequest['function'] && !$apiRequest['is_generic']) {
            _civicrm_api3_validate_fields($apiRequest['entity'], $apiRequest['action'], $apiRequest['params'], $fields);
            $result = isset($extra) ? $function($apiRequest['params'], $extra) : $function($apiRequest['params']);
        } else {
            return civicrm_api3_create_error("API (" . $apiRequest['entity'] . ", " . $apiRequest['action'] . ") does not exist (join the API team and implement it!)");
        }
        // For output filtering, process $apiWrappers in reverse order
        foreach (array_reverse($apiWrappers) as $apiWrapper) {
            $result = $apiWrapper->toApiOutput($apiRequest, $result);
        }
        if (CRM_Utils_Array::value('format.is_success', $apiRequest['params']) == 1) {
            if ($result['is_error'] === 0) {
                return 1;
            } else {
                return 0;
            }
        }
        if (!empty($apiRequest['params']['format.only_id']) && isset($result['id'])) {
            return $result['id'];
        }
        if (CRM_Utils_Array::value('is_error', $result, 0) == 0) {
            _civicrm_api_call_nested_api($apiRequest['params'], $result, $apiRequest['action'], $apiRequest['entity'], $apiRequest['version']);
        }
        if (function_exists('xdebug_time_index') && CRM_Utils_Array::value('debug', $apiRequest['params']) && is_array($result)) {
            $result['xdebug']['peakMemory'] = xdebug_peak_memory_usage();
            $result['xdebug']['memory'] = xdebug_memory_usage();
            $result['xdebug']['timeIndex'] = xdebug_time_index();
        }
        return $result;
    } catch (PEAR_Exception $e) {
        if (CRM_Utils_Array::value('format.is_success', $apiRequest['params']) == 1) {
            return 0;
        }
        $error = $e->getCause();
        if ($error instanceof DB_Error) {
            $data["error_code"] = DB::errorMessage($error->getCode());
            $data["sql"] = $error->getDebugInfo();
        }
        if (!empty($apiRequest['params']['debug'])) {
            if (method_exists($e, 'getUserInfo')) {
                $data['debug_info'] = $error->getUserInfo();
            }
            if (method_exists($e, 'getExtraData')) {
                $data['debug_info'] = $data + $error->getExtraData();
            }
            $data['trace'] = $e->getTraceAsString();
        } else {
            $data['tip'] = "add debug=1 to your API call to have more info about the error";
        }
        $err = civicrm_api3_create_error($e->getMessage(), $data, $apiRequest);
        if (!empty($apiRequest['is_transactional'])) {
            $transaction->rollback();
        }
        return $err;
    } catch (API_Exception $e) {
        if (!isset($apiRequest)) {
            $apiRequest = array();
        }
        if (CRM_Utils_Array::value('format.is_success', CRM_Utils_Array::value('params', $apiRequest)) == 1) {
            return 0;
        }
        $data = $e->getExtraParams();
        $data['entity'] = CRM_Utils_Array::value('entity', $apiRequest);
        $data['action'] = CRM_Utils_Array::value('action', $apiRequest);
        $err = civicrm_api3_create_error($e->getMessage(), $data, $apiRequest, $e->getCode());
        if (CRM_Utils_Array::value('debug', CRM_Utils_Array::value('params', $apiRequest)) && empty($data['trace'])) {
            $err['trace'] = $e->getTraceAsString();
        }
        if (!empty($apiRequest['is_transactional'])) {
            $transaction->rollback();
        }
        return $err;
    } catch (Exception $e) {
        if (CRM_Utils_Array::value('format.is_success', $apiRequest['params']) == 1) {
            return 0;
        }
        $data = array();
        $err = civicrm_api3_create_error($e->getMessage(), $data, $apiRequest, $e->getCode());
        if (!empty($apiRequest['params']['debug'])) {
            $err['trace'] = $e->getTraceAsString();
        }
        if (!empty($apiRequest['is_transactional'])) {
            $transaction->rollback();
        }
        return $err;
    }
}
コード例 #28
0
ファイル: Profile.php プロジェクト: nielosz/civicrm-core
/**
 * Submit a set of fields against a profile.
 *
 * Note choice of submit versus create is discussed CRM-13234 & related to the fact
 * 'profile' is being treated as a data-entry entity
 *
 * @param array $params
 *
 * @throws API_Exception
 * @return array
 *   API result array
 */
function civicrm_api3_profile_submit($params)
{
    $profileID = _civicrm_api3_profile_getProfileID($params['profile_id']);
    if (!CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFGroup', $profileID, 'is_active')) {
        //@todo declare pseudoconstant & let api do this
        throw new API_Exception('Invalid value for profile_id');
    }
    $isContactActivityProfile = CRM_Core_BAO_UFField::checkContactActivityProfileType($profileID);
    if (!empty($params['id']) && CRM_Core_BAO_UFField::checkProfileType($profileID) && !$isContactActivityProfile) {
        throw new API_Exception('Update profiles including more than one entity not currently supported');
    }
    $contactParams = $activityParams = $missingParams = array();
    $profileFields = civicrm_api3('Profile', 'getfields', array('action' => 'submit', 'profile_id' => $profileID));
    $profileFields = $profileFields['values'];
    if ($isContactActivityProfile) {
        civicrm_api3_verify_mandatory($params, NULL, array('activity_id'));
        $errors = CRM_Profile_Form::validateContactActivityProfile($params['activity_id'], $params['contact_id'], $profileID);
        if (!empty($errors)) {
            throw new API_Exception(array_pop($errors));
        }
    }
    foreach ($profileFields as $fieldName => $field) {
        if (!isset($params[$fieldName])) {
            continue;
        }
        $value = $params[$fieldName];
        if ($params[$fieldName] && isset($params[$fieldName . '_id'])) {
            $value = $params[$fieldName . '_id'];
        }
        $contactEntities = array('contact', 'individual', 'organization', 'household');
        $locationEntities = array('email', 'address', 'phone', 'website', 'im');
        $entity = strtolower(CRM_Utils_Array::value('entity', $field));
        if ($entity && !in_array($entity, array_merge($contactEntities, $locationEntities))) {
            $contactParams['api.' . $entity . '.create'][$fieldName] = $value;
            //@todo we are not currently declaring this option
            if (isset($params['batch_id']) && strtolower($entity) == 'contribution') {
                $contactParams['api.' . $entity . '.create']['batch_id'] = $params['batch_id'];
            }
            if (isset($params[$entity . '_id'])) {
                //todo possibly declare $entity_id in getfields ?
                $contactParams['api.' . $entity . '.create']['id'] = $params[$entity . '_id'];
            }
        } else {
            $contactParams[_civicrm_api3_profile_translate_fieldnames_for_bao($fieldName)] = $value;
        }
    }
    if (isset($contactParams['api.contribution.create']) && isset($contactParams['api.membership.create'])) {
        $contactParams['api.membership_payment.create'] = array('contribution_id' => '$value.api.contribution.create.id', 'membership_id' => '$value.api.membership.create.id');
    }
    if (isset($contactParams['api.contribution.create']) && isset($contactParams['api.participant.create'])) {
        $contactParams['api.participant_payment.create'] = array('contribution_id' => '$value.api.contribution.create.id', 'participant_id' => '$value.api.participant.create.id');
    }
    $contactParams['contact_id'] = CRM_Utils_Array::value('contact_id', $params);
    $contactParams['profile_id'] = $profileID;
    $contactParams['skip_custom'] = 1;
    $contactProfileParams = civicrm_api3_profile_apply($contactParams);
    // Contact profile fields
    $profileParams = $contactProfileParams['values'];
    // If profile having activity fields
    if ($isContactActivityProfile && !empty($activityParams)) {
        $activityParams['id'] = $params['activity_id'];
        $profileParams['api.activity.create'] = $activityParams;
    }
    return civicrm_api3('contact', 'create', $profileParams);
}
コード例 #29
0
ファイル: Case.php プロジェクト: archcidburnziso/civicrm-core
/**
* Delete a specified case.
*
* @param  array(
   //REQUIRED:
* 'id' => int
*
* //OPTIONAL
* 'move_to_trash' => bool (defaults to false)
*
* @return boolean: true if success, else false
* {@getfields case_delete}
* @access public
*/
function civicrm_api3_case_delete($params)
{
    //check parameters
    civicrm_api3_verify_mandatory($params, NULL, array('id'));
    if (CRM_Case_BAO_Case::deleteCase($params['id'], CRM_Utils_Array::value('move_to_trash', $params, FALSE))) {
        return civicrm_api3_create_success($params, $params, 'case', 'delete');
    } else {
        return civicrm_api3_create_error('Could not delete case.');
    }
}
コード例 #30
0
ファイル: utils.php プロジェクト: sugan2111/Drupal_code
/**
 * Function to do a 'standard' api del.
 *
 * When the api is only doing a $bao::del then use this if api::del doesn't exist it will try DAO delete method.
 *
 * @param string $bao_name
 * @param array $params
 *
 * @return array
 *   API result array
 * @throws API_Exception
 */
function _civicrm_api3_basic_delete($bao_name, &$params)
{
    civicrm_api3_verify_mandatory($params, NULL, array('id'));
    $args = array(&$params['id']);
    if (method_exists($bao_name, 'del')) {
        $bao = call_user_func_array(array($bao_name, 'del'), $args);
        if ($bao !== FALSE) {
            return civicrm_api3_create_success(TRUE);
        }
        throw new API_Exception('Could not delete entity id ' . $params['id']);
    } elseif (method_exists($bao_name, 'delete')) {
        $dao = new $bao_name();
        $dao->id = $params['id'];
        if ($dao->find()) {
            while ($dao->fetch()) {
                $dao->delete();
                return civicrm_api3_create_success();
            }
        } else {
            throw new API_Exception('Could not delete entity id ' . $params['id']);
        }
    }
    throw new API_Exception('no delete method found');
}