/** * This is a wrapper for the functions that return the results from the 'quasi-entity' mailing contact. * * @param array $params * @param bool $count * * @throws Exception */ function _civicrm_api3_mailing_contact_getresults($params, $count) { if (empty($params['type'])) { //ie. because the api is an anomaly & passing in id is not valid throw new Exception('This api call does not accept api as a parameter'); } $options = _civicrm_api3_get_options_from_params($params, TRUE, 'contribution', 'get'); $fnName = '_civicrm_api3_mailing_contact_get_' . strtolower($params['type']); return $fnName($params['contact_id'], $options['offset'], $options['limit'], $options['sort'], $count); }
/** * Returns array of groups matching a set of one or more Group properties. * * @param array $params * Array of properties. If empty, all records will be returned. * * @return array * Array of matching groups */ function civicrm_api3_group_get($params) { $options = _civicrm_api3_get_options_from_params($params, TRUE, 'Group', 'get'); if (empty($options['return']) || !in_array('member_count', $options['return'])) { return _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params, TRUE, 'Group'); } $groups = _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params, FALSE, 'Group'); foreach ($groups as $id => $group) { $groups[$id]['member_count'] = CRM_Contact_BAO_Group::memberCount($id); } return civicrm_api3_create_success($groups, $params, 'Group', 'get'); }
/** * Returns array of groups matching a set of one or more Group properties. * * @param array $params * Array of properties. If empty, all records will be returned. * * @return array * Array of matching groups */ function civicrm_api3_group_get($params) { $options = _civicrm_api3_get_options_from_params($params, TRUE, 'Group', 'get'); if ((empty($options['return']) || !in_array('member_count', $options['return'])) && empty($params['check_permissions'])) { return _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params, TRUE, 'Group'); } $groups = _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params, FALSE, 'Group'); foreach ($groups as $id => $group) { if (!empty($params['check_permissions']) && !CRM_Contact_BAO_Group::checkPermission($group['id'])) { unset($groups[$id]); } elseif (!empty($options['return']) && in_array('member_count', $options['return'])) { $groups[$id]['member_count'] = CRM_Contact_BAO_Group::memberCount($id); } } return civicrm_api3_create_success($groups, $params, 'Group', 'get'); }
/** * Get contact membership record. * * This api will return the membership records for the contacts * having membership based on the relationship with the direct members. * * @param Array $params key/value pairs for contact_id and some * options affecting the desired results; has legacy support * for just passing the contact_id itself as the argument * * @return Array of all found membership property values. * @access public * @todo needs some love - basically only a get for a given contact right now * {@getfields membership_get} */ function civicrm_api3_membership_get($params) { $activeOnly = $membershipTypeId = $membershipType = NULL; $contactID = CRM_Utils_Array::value('contact_id', $params); if (!empty($params['filters']) && is_array($params['filters'])) { $activeOnly = CRM_Utils_Array::value('is_current', $params['filters'], FALSE); } $activeOnly = CRM_Utils_Array::value('active_only', $params, $activeOnly); if (!empty($params['contact_id']) && !is_array($params['contact_id'])) { $membershipValues = _civicrm_api3_membership_get_customv2behaviour($params, $membershipTypeId, $activeOnly); } else { //legacy behaviour only ever worked when contact_id passed in - use standard api function otherwise $membershipValues = _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params, FALSE); } $options = _civicrm_api3_get_options_from_params($params, TRUE, 'membership', 'get'); $return = $options['return']; if (empty($membershipValues) || !empty($return) && !array_key_exists('related_contact_id', $return) && !array_key_exists('relationship_name', $return)) { return civicrm_api3_create_success($membershipValues, $params, 'membership', 'get'); } $members = _civicrm_api3_membership_relationsship_get_customv2behaviour($params, $membershipValues, $contactID); return civicrm_api3_create_success($members, $params, 'membership', 'get'); }
/** * Gets a CiviCRM activity according to parameters. * * @param array $params * Array per getfields documentation. * * @return array API result array * API result array * * @throws \API_Exception * @throws \CiviCRM_API3_Exception * @throws \Civi\API\Exception\UnauthorizedException */ function civicrm_api3_activity_get($params) { if (!empty($params['check_permissions']) && !CRM_Core_Permission::check('view all activities')) { // In absence of view all activities permission it's possible to see a specific activity by ACL. // Note still allowing view all activities to override ACLs is based on the 'don't change too much // if you are not sure principle' and it could be argued that the ACLs should always be applied. if (empty($params['id']) || !empty($params['contact_id'])) { // We fall back to the original blunt permissions if we don't have an id to check or we are about // to go to the weird place that the legacy 'contact_id' parameter takes us to. throw new \Civi\API\Exception\UnauthorizedException("Cannot access activities. Required permission: 'view all activities''"); } if (!CRM_Activity_BAO_Activity::checkPermission($params['id'], CRM_Core_Action::VIEW)) { throw new \Civi\API\Exception\UnauthorizedException('You do not have permission to view this activity'); } } if (!empty($params['contact_id'])) { $activities = CRM_Activity_BAO_Activity::getContactActivity($params['contact_id']); // BAO function doesn't actually return a contact ID - hack api for now & add to test so when api re-write // happens it won't get missed. foreach ($activities as $key => $activityArray) { $activities[$key]['id'] = $key; } } else { $sql = CRM_Utils_SQL_Select::fragment(); $options = civicrm_api3('ActivityContact', 'getoptions', array('field' => 'record_type_id')); $options = $options['values']; $activityContactOptions = array('target_contact_id' => array_search('Activity Targets', $options), 'source_contact_id' => array_search('Activity Source', $options), 'assignee_contact_id' => array_search('Activity Assignees', $options)); foreach ($activityContactOptions as $activityContactName => $activityContactValue) { if (!empty($params[$activityContactName])) { // If the intent is to have multiple joins -- one for each relation -- then you would // need different table aliases. Consider replacing 'ac' and passing in a '!alias' param, // with a different value for each relation. $sql->join('activity_' . $activityContactName, 'LEFT JOIN civicrm_activity_contact ac ON a.id = ac.activity_id AND ac.record_type_id = #typeId', array('typeId' => $activityContactValue)); $sql->where('ac.contact_id IN (#cid)', array('cid' => $params[$activityContactName])); } } $activities = _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params, FALSE, 'Activity', $sql); } $options = _civicrm_api3_get_options_from_params($params, FALSE, 'Activity', 'get'); if ($options['is_count']) { return civicrm_api3_create_success($activities, $params, 'Activity', 'get'); } $activities = _civicrm_api3_activity_get_formatResult($params, $activities); //legacy custom data get - so previous formatted response is still returned too return civicrm_api3_create_success($activities, $params, 'Activity', 'get'); }
/** * Retrieve a set of pledges, given a set of input params * * @param array $params (reference ) input parameters. Use interogate for possible fields * * @return array (reference ) array of pledges, if error an array with an error id and error message * {@getfields pledge_get} * @example PledgeGet.php * @access public */ function civicrm_api3_pledge_get($params) { $options = _civicrm_api3_get_options_from_params($params, TRUE, 'pledge', 'get'); if (empty($options['return'])) { $options['return'] = CRM_Pledge_BAO_Query::defaultReturnProperties(CRM_Contact_BAO_Query::MODE_PLEDGE); } else { $options['return']['pledge_id'] = 1; } $newParams = CRM_Contact_BAO_Query::convertFormValues($options['input_params']); $query = new CRM_Contact_BAO_Query($newParams, $options['return'], NULL, FALSE, FALSE, CRM_Contact_BAO_Query::MODE_PLEDGE); list($select, $from, $where) = $query->query(); $sql = "{$select} {$from} {$where}"; if (!empty($options['sort'])) { $sql .= " ORDER BY " . $options['sort']; } $sql .= " LIMIT " . $options['offset'] . " , " . $options['limit']; $dao = CRM_Core_DAO::executeQuery($sql); $pledge = array(); while ($dao->fetch()) { $pledge[$dao->pledge_id] = $query->store($dao); } return civicrm_api3_create_success($pledge, $params, 'pledge', 'get', $dao); }
/** * @param string $bao_name * Name of BAO * @param array $params * As passed into api get function. * @param bool $isFillUniqueFields * Do we need to ensure unique fields continue to be populated for this api? (backward compatibility). */ public function __construct($bao_name, $params, $isFillUniqueFields) { $this->bao = new $bao_name(); $this->entity = _civicrm_api_get_entity_name_from_dao($this->bao); $this->params = $params; $this->isFillUniqueFields = $isFillUniqueFields; $this->checkPermissions = \CRM_Utils_Array::value('check_permissions', $this->params, FALSE); $this->options = _civicrm_api3_get_options_from_params($this->params); $this->entityFieldNames = _civicrm_api3_field_names(_civicrm_api3_build_fields_array($this->bao)); // Call this function directly instead of using the api wrapper to force unique field names off require_once 'api/v3/Generic.php'; $apiSpec = \civicrm_api3_generic_getfields(array('entity' => $this->entity, 'version' => 3, 'params' => array('action' => 'get')), FALSE); $this->apiFieldSpec = $apiSpec['values']; $this->query = \CRM_Utils_SQL_Select::from($this->bao->tableName() . " a"); }
/** * @param string $baoName * Name of BAO * @param array $params * As passed into api get function. * @param bool $isFillUniqueFields * Do we need to ensure unique fields continue to be populated for this api? (backward compatibility). */ public function __construct($baoName, $params, $isFillUniqueFields) { $bao = new $baoName(); $this->entity = _civicrm_api_get_entity_name_from_dao($bao); $this->params = $params; $this->isFillUniqueFields = $isFillUniqueFields; $this->checkPermissions = \CRM_Utils_Array::value('check_permissions', $this->params, FALSE); $this->options = _civicrm_api3_get_options_from_params($this->params); $this->entityFieldNames = _civicrm_api3_field_names(_civicrm_api3_build_fields_array($bao)); // Call this function directly instead of using the api wrapper to force unique field names off require_once 'api/v3/Generic.php'; $apiSpec = \civicrm_api3_generic_getfields(array('entity' => $this->entity, 'version' => 3, 'params' => array('action' => 'get')), FALSE); $this->apiFieldSpec = $apiSpec['values']; $this->query = \CRM_Utils_SQL_Select::from($bao->tableName() . ' ' . self::MAIN_TABLE_ALIAS); $bao->free(); // Add ACLs first to avoid redundant subclauses $this->query->where($this->getAclClause(self::MAIN_TABLE_ALIAS, $baoName)); }
/** * Retrieve a set of contributions, given a set of input params * * @param array $params (reference ) input parameters * @param array $returnProperties Which properties should be included in the * returned Contribution object. If NULL, the default * set of properties will be included. * * @return array (reference ) array of contributions, if error an array with an error id and error message * @static void * @access public * {@getfields Contribution_get} * @example ContributionGet.php */ function civicrm_api3_contribution_get($params) { $options = _civicrm_api3_get_options_from_params($params, TRUE, 'contribution', 'get'); $sort = CRM_Utils_Array::value('sort', $options, NULL); $offset = CRM_Utils_Array::value('offset', $options); $rowCount = CRM_Utils_Array::value('limit', $options); $smartGroupCache = CRM_Utils_Array::value('smartGroupCache', $params); $inputParams = CRM_Utils_Array::value('input_params', $options, array()); $returnProperties = CRM_Utils_Array::value('return', $options, NULL); if (empty($returnProperties)) { $returnProperties = CRM_Contribute_BAO_Query::defaultReturnProperties(CRM_Contact_BAO_Query::MODE_CONTRIBUTE); } $newParams = CRM_Contact_BAO_Query::convertFormValues($inputParams); $query = new CRM_Contact_BAO_Query($newParams, $returnProperties, NULL, FALSE, FALSE, CRM_Contact_BAO_Query::MODE_CONTRIBUTE); list($select, $from, $where, $having) = $query->query(); $sql = "{$select} {$from} {$where} {$having}"; if (!empty($sort)) { $sql .= " ORDER BY {$sort} "; } $sql .= " LIMIT {$offset}, {$rowCount} "; $dao = CRM_Core_DAO::executeQuery($sql); $contribution = array(); while ($dao->fetch()) { //CRM-8662 $contribution_details = $query->store($dao); $softContribution = CRM_Contribute_BAO_ContributionSoft::getSoftContribution($dao->contribution_id, TRUE); $contribution[$dao->contribution_id] = array_merge($contribution_details, $softContribution); if (isset($contribution[$dao->contribution_id]['financial_type_id'])) { $contribution[$dao->contribution_id]['financial_type_id'] = $contribution[$dao->contribution_id]['financial_type_id']; } // format soft credit for backward compatibility _civicrm_api3_format_soft_credit($contribution[$dao->contribution_id]); } return civicrm_api3_create_success($contribution, $params, 'contribution', 'get', $dao); }
/** * Retrieve a specific participant, given a set of input params * If more than one matching participant exists, return an error, unless * the client has requested to return the first found contact * * @param array $params (reference ) input parameters * * @return array (reference ) array of properties, if error an array with an error id and error message * {@getfields participant_get} * @access public */ function civicrm_api3_participant_get($params) { $options = _civicrm_api3_get_options_from_params($params, TRUE, 'participant', 'get'); $sort = CRM_Utils_Array::value('sort', $options, NULL); $offset = CRM_Utils_Array::value('offset', $options); $rowCount = CRM_Utils_Array::value('limit', $options); $smartGroupCache = CRM_Utils_Array::value('smartGroupCache', $params); $inputParams = CRM_Utils_Array::value('input_params', $options, array()); $returnProperties = CRM_Utils_Array::value('return', $options, NULL); if (empty($returnProperties)) { $returnProperties = CRM_Event_BAO_Query::defaultReturnProperties(CRM_Contact_BAO_Query::MODE_EVENT); } $newParams = CRM_Contact_BAO_Query::convertFormValues($inputParams); $query = new CRM_Contact_BAO_Query($newParams, $returnProperties, NULL, FALSE, FALSE, CRM_Contact_BAO_Query::MODE_EVENT); list($select, $from, $where, $having) = $query->query(); $sql = "{$select} {$from} {$where} {$having}"; if (!empty($sort)) { $sql .= " ORDER BY {$sort} "; } $sql .= " LIMIT {$offset}, {$rowCount} "; $dao = CRM_Core_DAO::executeQuery($sql); $participant = array(); while ($dao->fetch()) { $participant[$dao->participant_id] = $query->store($dao); _civicrm_api3_custom_data_get($participant[$dao->participant_id], 'Participant', $dao->participant_id, NULL); } return civicrm_api3_create_success($participant, $params, 'participant', 'get', $dao); }
/** * Gets a CiviCRM activity according to parameters. * * @param array $params * Array per getfields documentation. * * @return array * API result array */ function civicrm_api3_activity_get($params) { if (!empty($params['contact_id'])) { $activities = CRM_Activity_BAO_Activity::getContactActivity($params['contact_id']); // BAO function doesn't actually return a contact ID - hack api for now & add to test so when api re-write // happens it won't get missed. foreach ($activities as $key => $activityArray) { $activities[$key]['id'] = $key; } } else { $activities = _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params, FALSE, 'Activity'); } $options = _civicrm_api3_get_options_from_params($params, FALSE, 'Activity', 'get'); if ($options['is_count']) { return civicrm_api3_create_success($activities, $params, 'Activity', 'get'); } $activities = _civicrm_api3_activity_get_formatResult($params, $activities); //legacy custom data get - so previous formatted response is still returned too return civicrm_api3_create_success($activities, $params, 'Activity', 'get'); }
/** * Get Event record. * * * @param array $params an associative array of name/value property values of civicrm_event * {@getfields event_get} * * @return Array of all found event property values. * @access public * */ function civicrm_api3_event_get($params) { //legacy support for $params['return.sort'] if (!empty($params['return.sort'])) { $params['options']['sort'] = $params['return.sort']; unset($params['return.sort']); } //legacy support for $params['return.offset'] if (!empty($params['return.offset'])) { $params['options']['offset'] = $params['return.offset']; unset($params['return.offset']); } //legacy support for $params['return.max_results'] if (!empty($params['return.max_results'])) { $params['options']['limit'] = $params['return.max_results']; unset($params['return.max_results']); } $eventDAO = new CRM_Event_BAO_Event(); _civicrm_api3_dao_set_filter($eventDAO, $params, TRUE, 'Event'); if (!empty($params['is_template'])) { $eventDAO->whereAdd('( is_template = 1 )'); } elseif (empty($eventDAO->id)) { $eventDAO->whereAdd('( is_template IS NULL ) OR ( is_template = 0 )'); } if (!empty($params['isCurrent'])) { $eventDAO->whereAdd('(start_date >= CURDATE() || end_date >= CURDATE())'); } // @todo should replace all this with _civicrm_api3_dao_to_array($bao, $params, FALSE, $entity) - but we still have // the return.is_full to deal with. // NB the std dao_to_array function should only return custom if required. $event = array(); $options = _civicrm_api3_get_options_from_params($params); $eventDAO->find(); while ($eventDAO->fetch()) { $event[$eventDAO->id] = array(); CRM_Core_DAO::storeValues($eventDAO, $event[$eventDAO->id]); if (!empty($params['return.is_full'])) { _civicrm_api3_event_getisfull($event, $eventDAO->id); } _civicrm_api3_event_get_legacy_support_42($event, $eventDAO->id); _civicrm_api3_custom_data_get($event[$eventDAO->id], 'Event', $eventDAO->id, NULL, $eventDAO->event_type_id); if (!empty($options['return'])) { $event[$eventDAO->id]['price_set_id'] = CRM_Price_BAO_PriceSet::getFor('civicrm_event', $eventDAO->id); } } //end of the loop return civicrm_api3_create_success($event, $params, 'event', 'get', $eventDAO); }
/** * Gets a CiviCRM activity according to parameters. * * @param array $params * Array per getfields documentation. * * @return array * API result array */ function civicrm_api3_activity_get($params) { if (!empty($params['contact_id'])) { $activities = CRM_Activity_BAO_Activity::getContactActivity($params['contact_id']); // BAO function doesn't actually return a contact ID - hack api for now & add to test so when api re-write // happens it won't get missed. foreach ($activities as $key => $activityArray) { $activities[$key]['id'] = $key; } } else { $extraSql = array(); $options = civicrm_api3('ActivityContact', 'getoptions', array('field' => 'record_type_id')); $options = $options['values']; $activityContactOptions = array('target_contact_id' => array_search('Activity Targets', $options), 'source_contact_id' => array_search('Activity Source', $options), 'assignee_contact_id' => array_search('Activity Assignees', $options)); foreach ($activityContactOptions as $activityContactName => $activityContactValue) { if (!empty($params[$activityContactName])) { $extraSql['join'][] = array('activity_' . $activityContactName => ' LEFT JOIN civicrm_activity_contact ac ON a.id = ac.activity_id AND ac.record_type_id = ' . (int) $activityContactValue); // Note that if we later need to change the int to an array we would need sql escaping. $extraSql['where'] = array('activity_' . $activityContactName => 'ac.contact_id = ' . (int) $params[$activityContactName]); } } $activities = _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params, FALSE, 'Activity', $extraSql); } $options = _civicrm_api3_get_options_from_params($params, FALSE, 'Activity', 'get'); if ($options['is_count']) { return civicrm_api3_create_success($activities, $params, 'Activity', 'get'); } $activities = _civicrm_api3_activity_get_formatResult($params, $activities); //legacy custom data get - so previous formatted response is still returned too return civicrm_api3_create_success($activities, $params, 'Activity', 'get'); }
/** * Returns array of groups matching a set of one or more group properties * * @param array $params (referance) Array of one or more valid * property_name=>value pairs. If $params is set * as null, all groups will be returned * * @return array Array of matching groups * @example GroupGet.php * {@getfields group_get} * @access public */ function civicrm_api3_group_get($params) { $options = _civicrm_api3_get_options_from_params($params, TRUE, 'group', 'get'); $sort = CRM_Utils_Array::value('sort', $options, NULL); $offset = CRM_Utils_Array::value('offset', $options); $rowCount = CRM_Utils_Array::value('limit', $options); $returnProperties = CRM_Utils_Array::value('return', $options, NULL); $inputParams = CRM_Utils_Array::value('input_params', $options, array()); if (is_array($returnProperties) && !empty($returnProperties)) { // group function takes $returnProperties in non standard format & doesn't add id unset($returnProperties['group_id']); $returnProperties['id'] = 1; $returnProperties = array_keys($returnProperties); } if (!empty($inputParams['group_id'])) { $inputParams['id'] = $inputParams['group_id']; } $groupObjects = CRM_Contact_BAO_Group::getGroups($inputParams, $returnProperties, $sort, $offset, $rowCount); if (empty($groupObjects)) { return civicrm_api3_create_success(FALSE); } $groups = array(); foreach ($groupObjects as $group) { _civicrm_api3_object_to_array($group, $groups[$group->id]); _civicrm_api3_custom_data_get($groups[$group->id], 'Group', $group->id); } return civicrm_api3_create_success($groups, $params, 'group', 'create'); }
function _civicrm_api3_apply_options_to_dao(&$params, &$dao, $entity) { $options = _civicrm_api3_get_options_from_params($params, false, $entity); $dao->limit((int) $options['offset'], (int) $options['limit']); if (!empty($options['sort'])) { $dao->orderBy($options['sort']); } }
/** * Get Event record. * * @param array $params * * @return array * Array of all found event property values. */ function civicrm_api3_event_get($params) { //legacy support for $params['return.sort'] if (!empty($params['return.sort'])) { $params['options']['sort'] = $params['return.sort']; unset($params['return.sort']); } //legacy support for $params['return.offset'] if (!empty($params['return.offset'])) { $params['options']['offset'] = $params['return.offset']; unset($params['return.offset']); } //legacy support for $params['return.max_results'] if (!empty($params['return.max_results'])) { $params['options']['limit'] = $params['return.max_results']; unset($params['return.max_results']); } $sql = CRM_Utils_SQL_Select::fragment(); if (!empty($params['isCurrent'])) { $sql->where('(start_date >= CURDATE() || end_date >= CURDATE())'); } $events = _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params, FALSE, 'Event', $sql, TRUE); $options = _civicrm_api3_get_options_from_params($params); if ($options['is_count']) { return civicrm_api3_create_success($events, $params, 'Event', 'get'); } foreach ($events as $id => $event) { if (!empty($params['return.is_full'])) { _civicrm_api3_event_getisfull($events, $id); } _civicrm_api3_event_get_legacy_support_42($events, $id); if (!empty($options['return'])) { $events[$id]['price_set_id'] = CRM_Price_BAO_PriceSet::getFor('civicrm_event', $id); } } return civicrm_api3_create_success($events, $params, 'Event', 'get'); }
/** * A generic "get" API based on simple array data. This is comparable to * _civicrm_api3_basic_get but does not use DAO/BAO. This is useful for * small/mid-size data loaded from external JSON or XML documents. * * @param array $params * API parameters. * @param array $records * List of all records. * @param string $idCol * The property which defines the ID of a record * @param array $fields * List of filterable fields. * @return array */ function _civicrm_api3_basic_array_get($entity, $params, $records, $idCol, $fields) { $options = _civicrm_api3_get_options_from_params($params, TRUE, $entity, 'get'); // TODO // $sort = CRM_Utils_Array::value('sort', $options, NULL); $offset = CRM_Utils_Array::value('offset', $options); $limit = CRM_Utils_Array::value('limit', $options); $matches = array(); $currentOffset = 0; foreach ($records as $record) { if ($idCol != 'id') { $record['id'] = $record[$idCol]; } $match = TRUE; foreach ($params as $k => $v) { if ($k == 'id') { $k = $idCol; } if (in_array($k, $fields) && $record[$k] != $v) { $match = FALSE; break; } } if ($match) { if ($currentOffset >= $offset) { $matches[$record[$idCol]] = $record; } if ($limit && count($matches) >= $limit) { break; } $currentOffset++; } } $return = CRM_Utils_Array::value('return', $options, array()); if (!empty($return)) { $return['id'] = 1; $matches = CRM_Utils_Array::filterColumns($matches, array_keys($return)); } return civicrm_api3_create_success($matches, $params); }
/** * Determine if custom fields need to be retrieved. * * We currently retrieve all custom fields or none at this level so if we know the entity * && it can take custom fields & there is the string 'custom' in their return request we get them all, they are filtered on the way out * @todo filter so only required fields are queried * * @param string $entity * Entity name in CamelCase. * @param array $params * * @return bool */ function _civicrm_api3_custom_fields_are_required($entity, $params) { if (!array_key_exists($entity, CRM_Core_BAO_CustomQuery::$extendsMap)) { return FALSE; } $options = _civicrm_api3_get_options_from_params($params); // We check for possibility of 'custom' => 1 as well as specific custom fields. $returnString = implode('', $options['return']) . implode('', array_keys($options['return'])); if (stristr($returnString, 'custom')) { return TRUE; } }
/** * @param array $apiRequest * Parsed API request. * @return string|TRUE * If match, return TRUE. Otherwise, return a string with an error code. */ public function matches($apiRequest) { if (!$this->isValid()) { return 'invalid'; } if ($this->version != $apiRequest['version']) { return 'version'; } if ($this->entity !== '*' && $this->entity !== $apiRequest['entity']) { return 'entity'; } if ($this->actions !== '*' && !in_array($apiRequest['action'], $this->actions)) { return 'action'; } // These params *must* be included for the API request to proceed. foreach ($this->required as $param => $value) { if (!isset($apiRequest['params'][$param])) { return 'required-missing-' . $param; } if ($value !== '*' && $apiRequest['params'][$param] != $value) { return 'required-wrong-' . $param; } } // These params *may* be included at the caller's discretion if ($this->fields !== '*') { $activatedFields = array_keys($apiRequest['params']); $activatedFields = preg_grep('/^api\\./', $activatedFields, PREG_GREP_INVERT); if ($apiRequest['action'] == 'get') { // Kind'a silly we need to (re(re))parse here for each rule; would be more // performant if pre-parsed by Request::create(). $options = _civicrm_api3_get_options_from_params($apiRequest['params'], TRUE, $apiRequest['entity'], 'get'); $return = \CRM_Utils_Array::value('return', $options, array()); $activatedFields = array_merge($activatedFields, array_keys($return)); } $unknowns = array_diff($activatedFields, array_keys($this->required), $this->fields, self::$IGNORE_FIELDS); if (!empty($unknowns)) { return 'unknown-' . implode(',', $unknowns); } } return TRUE; }
/** * Civixero.ContactPull API. * * @param array $params * * @return array * API result descriptor * * @see civicrm_api3_create_success * @see civicrm_api3_create_error * @throws API_Exception */ function civicrm_api3_civixero_invoicepush($params) { $options = _civicrm_api3_get_options_from_params($params); $xero = new CRM_Civixero_Invoice($params); $xero->push($params, $options['limit']); }
/** * Get report template rows. * * @param array $params * * @return array * @throws API_Exception * @throws CiviCRM_API3_Exception */ function _civicrm_api3_report_template_getrows($params) { if (empty($params['report_id'])) { $params['report_id'] = civicrm_api3('report_instance', 'getvalue', array('id' => $params['instance_id'], 'return' => 'report_id')); } $class = (string) civicrm_api3('option_value', 'getvalue', array('option_group_name' => 'report_template', 'return' => 'name', 'value' => $params['report_id'])); $reportInstance = new $class(); if (!empty($params['instance_id'])) { $reportInstance->setID($params['instance_id']); } $reportInstance->setParams($params); $reportInstance->noController = TRUE; $reportInstance->preProcess(); $reportInstance->setDefaultValues(FALSE); $reportInstance->setParams(array_merge($reportInstance->getDefaultValues(), $params)); $options = _civicrm_api3_get_options_from_params($params, TRUE, 'ReportTemplate', 'get'); $reportInstance->setLimitValue($options['limit']); $reportInstance->setAddPaging(FALSE); $reportInstance->setOffsetValue($options['offset']); $reportInstance->beginPostProcessCommon(); $sql = $reportInstance->buildQuery(); $rows = $metadata = $requiredMetadata = array(); $reportInstance->buildRows($sql, $rows); $reportInstance->formatDisplay($rows); if (isset($params['options']) && !empty($params['options']['metadata'])) { $requiredMetadata = $params['options']['metadata']; if (in_array('title', $requiredMetadata)) { $metadata['metadata']['title'] = $reportInstance->getTitle(); } if (in_array('labels', $requiredMetadata)) { foreach ($reportInstance->_columnHeaders as $key => $header) { // Would be better just to expect reports to provide titles but reports are not consistent so we anticipate empty //NB I think these are already translated $metadata['metadata']['labels'][$key] = !empty($header['title']) ? $header['title'] : ''; } } if (in_array('sql', $requiredMetadata)) { $metadata['metadata']['sql'] = $reportInstance->getReportSql(); } } return array($rows, $reportInstance, $metadata); }
/** * Gets a CiviCRM activity according to parameters. * * @param array $params * Array per getfields documentation. * * @return array * API result array */ function civicrm_api3_activity_get($params) { if (!empty($params['contact_id'])) { $activities = CRM_Activity_BAO_Activity::getContactActivity($params['contact_id']); // BAO function doesn't actually return a contact ID - hack api for now & add to test so when api re-write // happens it won't get missed. foreach ($activities as $key => $activityArray) { $activities[$key]['id'] = $key; } } else { $sql = CRM_Utils_SQL_Select::fragment(); $options = civicrm_api3('ActivityContact', 'getoptions', array('field' => 'record_type_id')); $options = $options['values']; $activityContactOptions = array('target_contact_id' => array_search('Activity Targets', $options), 'source_contact_id' => array_search('Activity Source', $options), 'assignee_contact_id' => array_search('Activity Assignees', $options)); foreach ($activityContactOptions as $activityContactName => $activityContactValue) { if (!empty($params[$activityContactName])) { // If the intent is to have multiple joins -- one for each relation -- then you would // need different table aliases. Consider replacing 'ac' and passing in a '!alias' param, // with a different value for each relation. $sql->join('activity_' . $activityContactName, 'LEFT JOIN civicrm_activity_contact ac ON a.id = ac.activity_id AND ac.record_type_id = #typeId', array('typeId' => $activityContactValue)); $sql->where('ac.contact_id IN (#cid)', array('cid' => $params[$activityContactName])); } } $activities = _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params, FALSE, 'Activity', $sql); } $options = _civicrm_api3_get_options_from_params($params, FALSE, 'Activity', 'get'); if ($options['is_count']) { return civicrm_api3_create_success($activities, $params, 'Activity', 'get'); } $activities = _civicrm_api3_activity_get_formatResult($params, $activities); //legacy custom data get - so previous formatted response is still returned too return civicrm_api3_create_success($activities, $params, 'Activity', 'get'); }
/** * Returns array of loc_blocks matching a set of one or more properties. * * @param array $params * Array of one or more valid property_name=>value pairs. If $params is set. * as null, all loc_blocks will be returned (default limit is 25). * * @return array * API result array. */ function civicrm_api3_loc_block_get($params) { $options = _civicrm_api3_get_options_from_params($params); // If a return param has been set then fetch the appropriate fk objects // This is a helper because api chaining does not work with a key like 'email_2'. if (!empty($options['return'])) { unset($params['return']); $values = array(); $items = array('address', 'email', 'phone', 'im'); $returnAll = !empty($options['return']['all']); foreach (_civicrm_api3_basic_get('CRM_Core_DAO_LocBlock', $params, FALSE) as $val) { foreach ($items as $item) { foreach (array('', '_2') as $suf) { $key = $item . $suf; if (!empty($val[$key . '_id']) && ($returnAll || !empty($options['return'][$key]))) { $val[$key] = civicrm_api($item, 'getsingle', array('version' => 3, 'id' => $val[$key . '_id'])); } } } $values[$val['id']] = $val; } return civicrm_api3_create_success($values, $params, 'LocBlock', 'get'); } return _civicrm_api3_basic_get('CRM_Core_DAO_LocBlock', $params); }
/** * Get contact Membership record. * * This api will return the membership records for the contacts * having membership based on the relationship with the direct members. * * @param array $params * Key/value pairs for contact_id and some. * options affecting the desired results; has legacy support * for just passing the contact_id itself as the argument * * @return array * Array of all found membership property values. */ function civicrm_api3_membership_get($params) { $activeOnly = $membershipTypeId = $membershipType = NULL; $contactID = CRM_Utils_Array::value('contact_id', $params); if (!empty($params['filters']) && is_array($params['filters']) && isset($params['filters']['is_current'])) { $activeOnly = $params['filters']['is_current']; unset($params['filters']['is_current']); } $activeOnly = CRM_Utils_Array::value('active_only', $params, $activeOnly); if ($activeOnly && empty($params['status_id'])) { $params['status_id'] = array('IN' => CRM_Member_BAO_MembershipStatus::getMembershipStatusCurrent()); } $options = _civicrm_api3_get_options_from_params($params, TRUE, 'Membership', 'get'); if ($options['is_count']) { return _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params); } $membershipValues = _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params, FALSE, 'Membership'); $return = $options['return']; if (empty($membershipValues) || !empty($return) && !array_key_exists('related_contact_id', $return) && !array_key_exists('relationship_name', $return)) { return civicrm_api3_create_success($membershipValues, $params, 'Membership', 'get'); } $members = _civicrm_api3_membership_relationsship_get_customv2behaviour($params, $membershipValues, $contactID); return civicrm_api3_create_success($members, $params, 'Membership', 'get'); }
/** * Get details of a particular case, or search for cases, depending on params. * * Please provide one (and only one) of the four get/search parameters: * * @param array $params * 'id' => if set, will get all available info about a case, including contacts and activities * * // if no case_id provided, this function will use one of the following search parameters: * 'client_id' => finds all cases with a specific client * 'activity_id' => returns the case containing a specific activity * 'contact_id' => finds all cases associated with a contact (in any role, not just client) * * @throws API_Exception * @return array * (get mode, case_id provided): Array with case details, case roles, case activity ids, (search mode, case_id not provided): Array of cases found */ function civicrm_api3_case_get($params) { $options = _civicrm_api3_get_options_from_params($params); $sql = CRM_Utils_SQL_Select::fragment(); // Add clause to search by client if (!empty($params['contact_id'])) { $contacts = array(); foreach ((array) $params['contact_id'] as $c) { if (!CRM_Utils_Rule::positiveInteger($c)) { throw new API_Exception('Invalid parameter: contact_id. Must provide numeric value(s).'); } $contacts[] = $c; } $sql->join('civicrm_case_contact', 'INNER JOIN civicrm_case_contact ON civicrm_case_contact.case_id = a.id')->where('civicrm_case_contact.contact_id IN (' . implode(',', $contacts) . ')'); } // Add clause to search by activity if (!empty($params['activity_id'])) { if (!CRM_Utils_Rule::positiveInteger($params['activity_id'])) { throw new API_Exception('Invalid parameter: activity_id. Must provide a numeric value.'); } $activityId = $params['activity_id']; $originalId = CRM_Core_DAO::getFieldValue('CRM_Activity_BAO_Activity', $activityId, 'original_id'); if ($originalId) { $activityId .= ',' . $originalId; } $sql->join('civicrm_case_activity', 'INNER JOIN civicrm_case_activity ON civicrm_case_activity.case_id = a.id')->where("civicrm_case_activity.activity_id IN ({$activityId})"); } $foundcases = _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params, TRUE, 'Case', $sql); if (empty($options['is_count'])) { // For historic reasons we return these by default only when fetching a case by id if (!empty($params['id']) && empty($options['return'])) { $options['return'] = array('contacts' => 1, 'activities' => 1, 'contact_id' => 1); } foreach ($foundcases['values'] as &$case) { _civicrm_api3_case_read($case, $options); } } return $foundcases; }
/** * Function to get the relationship * * @param array $params input parameters. * @todo Result is inconsistent depending on whether contact_id is passed in : * - if you pass in contact_id - it just returns all relationships for 'contact_id' * - if you don't pass in contact_id then it does a filter on the relationship table (DAO based search) * * @return Array API Result Array * {@getfields relationship_get} * @example RelationshipGet.php * @access public */ function civicrm_api3_relationship_get($params) { $options = _civicrm_api3_get_options_from_params($params); if (empty($params['contact_id'])) { if (!empty($params['membership_type_id']) && empty($params['relationship_type_id'])) { CRM_Contact_BAO_Relationship::membershipTypeToRelationshipTypes($params); } $relationships = _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params, FALSE); } else { $relationships = array(); $relationships = CRM_Contact_BAO_Relationship::getRelationship($params['contact_id'], CRM_Utils_Array::value('status_id', $params), 0, CRM_Utils_Array::value('is_count', $options), CRM_Utils_Array::value('id', $params), NULL, NULL, FALSE, $params); } //perhaps we should add a 'getcount' but at this stage lets just handle getcount output if ($options['is_count']) { return array('count' => $relationships); } foreach ($relationships as $relationshipId => $values) { _civicrm_api3_custom_data_get($relationships[$relationshipId], 'Relationship', $relationshipId, NULL, CRM_Utils_Array::value('relationship_type_id', $values)); } return civicrm_api3_create_success($relationships, $params); }
/** * Get details of a particular case, or search for cases, depending on params * * Please provide one (and only one) of the four get/search parameters: * * @param array( 'id' => if set, will get all available info about a case, including contacts and activities * * // if no case_id provided, this function will use one of the following search parameters: * 'client_id' => finds all cases with a specific client * 'activity_id' => returns the case containing a specific activity * 'contact_id' => finds all cases associated with a contact (in any role, not just client) * * {@getfields case_get} * * @return (get mode, case_id provided): Array with case details, case roles, case activity ids, (search mode, case_id not provided): Array of cases found * @access public * @todo Erik Hommel 16 dec 2010 check if all DB fields are returned */ function civicrm_api3_case_get($params) { $options = _civicrm_api3_get_options_from_params($params); //search by client if (!empty($params['contact_id'])) { $ids = array(); foreach ((array) $params['contact_id'] as $cid) { if (is_numeric($cid)) { $ids = array_merge($ids, CRM_Case_BAO_Case::retrieveCaseIdsByContactId($cid, TRUE)); } } $cases = array(); foreach ($ids as $id) { if ($case = _civicrm_api3_case_read($id, $options)) { $cases[$id] = $case; } } return civicrm_api3_create_success($cases, $params, 'case', 'get'); } //search by activity if (!empty($params['activity_id'])) { if (!is_numeric($params['activity_id'])) { return civicrm_api3_create_error('Invalid parameter: activity_id. Must provide a numeric value.'); } $caseId = CRM_Case_BAO_Case::getCaseIdByActivityId($params['activity_id']); if (!$caseId) { return civicrm_api3_create_success(array(), $params, 'case', 'get'); } $case = array($caseId => _civicrm_api3_case_read($caseId, $options)); return civicrm_api3_create_success($case, $params, 'case', 'get'); } //search by contacts if ($contact = CRM_Utils_Array::value('contact_id', $params)) { if (!is_numeric($contact)) { return civicrm_api3_create_error('Invalid parameter: contact_id. Must provide a numeric value.'); } $sql = "\nSELECT DISTINCT case_id\n FROM civicrm_relationship\n WHERE (contact_id_a = {$contact}\n OR contact_id_b = {$contact})\n AND case_id IS NOT NULL"; $dao =& CRM_Core_DAO::executeQuery($sql); $cases = array(); while ($dao->fetch()) { $cases[$dao->case_id] = _civicrm_api3_case_read($dao->case_id, $options); } return civicrm_api3_create_success($cases, $params, 'case', 'get'); } // For historic reasons we always return these when an id is provided $caseId = CRM_Utils_Array::value('id', $params); if ($caseId) { $options['return'] = array('contacts' => 1, 'activities' => 1); } $foundcases = _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params, TRUE, 'Case'); $cases = array(); foreach ($foundcases['values'] as $foundcase) { if ($case = _civicrm_api3_case_read($foundcase['id'], $options)) { $cases[$foundcase['id']] = $case; } } return civicrm_api3_create_success($cases, $params, 'case', 'get'); }
function civicrm_api3_contact_getstat ($params) { // mostly copy pasted from contact_get and the functions called by it $options = array(); _civicrm_api3_contact_get_supportanomalies($params, $options); $contacts = _civicrm_api3_get_using_query_object('contact', $params, $options); $options = _civicrm_api3_get_options_from_params($params, TRUE); $inputParams = CRM_Utils_Array::value('input_params', $options, array()); $returnProperties = CRM_Utils_Array::value('return', $options, array()); if(!empty($params['check_permissions'])){ // we will filter query object against getfields $fields = civicrm_api("contact", 'getfields', array('version' => 3, 'action' => 'get')); // we need to add this in as earlier in this function 'id' was unset in favour of $entity_id $fields['values'][$entity . '_id'] = array(); $varsToFilter = array('returnProperties', 'inputParams'); foreach ($varsToFilter as $varToFilter){ if(!is_array($$varToFilter)){ continue; } $$varToFilter = array_intersect_key($$varToFilter, $fields['values']); } } // $options = array_merge($options,$additional_options); $sort = CRM_Utils_Array::value('sort', $options, NULL); $returnSQL = CRM_Utils_Array::value('sql', $options, CRM_Utils_Array::value('options_sql', $options['input_params'])); $smartGroupCache = CRM_Utils_Array::value('smartGroupCache', $params); $newParams = CRM_Contact_BAO_Query::convertFormValues($inputParams); $skipPermissions = CRM_Utils_Array::value('check_permissions', $params)? 0 :1; $query = new CRM_Contact_BAO_Query( $params, $returnProperties, NULL, TRUE, FALSE, 1, $skipPermissions, TRUE, $smartGroupCache ); //this should add a check for view deleted if permissions are enabled if ($skipPermissions){ $query->_skipDeleteClause = TRUE; } $query->generatePermissionClause(FALSE, $count); list($select, $from, $where, $having) = $query->query($count); $options = $query->_options; if(!empty($query->_permissionWhereClause)){ if (empty($where)) { $where = "WHERE $query->_permissionWhereClause"; } else { $where = "$where AND $query->_permissionWhereClause"; } } $sql = "$select $from $where $having"; if (!empty($returnProperties)) { $extra = array(); $sql = "SELECT count(*) AS total,". substr ($sql, 34,10000); //replace select contact_id, by select count(*) $sql .= " GROUP BY ". implode (",",array_keys($returnProperties)) ; } else { $sql = "SELECT count(*) AS total $from $where $having"; $extra = array ("tip"=>"if you need to group by a field, use the return param, eg return=contact_type,gender", "warning"=> "use getcount, getstat without param might be blocked in the future"); if (!empty($sort)) { $sql .= " ORDER BY $sort "; } else { $sql .= " ORDER BY total DESC "; } } if ($returnSQL) { return array("is_error"=>1,"sql"=>$sql,"from"=>$from,"where"=>$where,"having"=>$having); } $dao = CRM_Core_DAO::executeQuery($sql); $values = array(); while ($dao->fetch()) { $values[] = $dao->toArray(); } return civicrm_api3_create_success($values, $params, "contact", "getstat", $dao,$extra); }