332438f44f94659fe1c8167dfe2186d9f0f55c2b
[civicrm-core.git] / api / v3 / Generic / Getlist.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
26 */
27
28 /**
29 * @package CiviCRM_APIv3
30 */
31
32 /**
33 * Generic api wrapper used for quicksearch and autocomplete.
34 *
35 * @param array $apiRequest
36 *
37 * @return mixed
38 */
39 function civicrm_api3_generic_getList($apiRequest) {
40 $entity = _civicrm_api_get_entity_name_from_camel($apiRequest['entity']);
41 $request = $apiRequest['params'];
42 $meta = civicrm_api3_generic_getfields(['action' => 'get'] + $apiRequest, FALSE);
43
44 // Hey api, would you like to provide default values?
45 $fnName = "_civicrm_api3_{$entity}_getlist_defaults";
46 $defaults = function_exists($fnName) ? $fnName($request) : [];
47 _civicrm_api3_generic_getList_defaults($entity, $request, $defaults, $meta['values']);
48
49 // Hey api, would you like to format the search params?
50 $fnName = "_civicrm_api3_{$entity}_getlist_params";
51 $fnName = function_exists($fnName) ? $fnName : '_civicrm_api3_generic_getlist_params';
52 $fnName($request);
53
54 $request['params']['check_permissions'] = !empty($apiRequest['params']['check_permissions']);
55 $result = civicrm_api3($entity, 'get', $request['params']);
56
57 // Hey api, would you like to format the output?
58 $fnName = "_civicrm_api3_{$entity}_getlist_output";
59 $fnName = function_exists($fnName) ? $fnName : '_civicrm_api3_generic_getlist_output';
60 $values = $fnName($result, $request, $entity, $meta['values']);
61
62 _civicrm_api3_generic_getlist_postprocess($result, $request, $values);
63
64 $output = ['page_num' => $request['page_num']];
65
66 // Limit is set for searching but not fetching by id
67 if (!empty($request['params']['options']['limit'])) {
68 // If we have an extra result then this is not the last page
69 $last = $request['params']['options']['limit'] - 1;
70 $output['more_results'] = isset($values[$last]);
71 unset($values[$last]);
72 }
73
74 return civicrm_api3_create_success($values, $request['params'], $entity, 'getlist', CRM_Core_DAO::$_nullObject, $output);
75 }
76
77 /**
78 * Set defaults for api.getlist.
79 *
80 * @param string $entity
81 * @param array $request
82 * @param array $apiDefaults
83 * @param array $fields
84 */
85 function _civicrm_api3_generic_getList_defaults($entity, &$request, $apiDefaults, $fields) {
86 $defaults = [
87 'page_num' => 1,
88 'input' => '',
89 'image_field' => NULL,
90 'color_field' => isset($fields['color']) ? 'color' : NULL,
91 'id_field' => $entity == 'option_value' ? 'value' : 'id',
92 'description_field' => [],
93 'add_wildcard' => Civi::settings()->get('includeWildCardInName'),
94 'params' => [],
95 'extra' => [],
96 ];
97 // Find main field from meta
98 foreach (['sort_name', 'title', 'label', 'name', 'subject'] as $field) {
99 if (isset($fields[$field])) {
100 $defaults['label_field'] = $defaults['search_field'] = $field;
101 break;
102 }
103 }
104 // Find fields to be used for the description
105 foreach (['description'] as $field) {
106 if (isset($fields[$field])) {
107 $defaults['description_field'][] = $field;
108 }
109 }
110 $resultsPerPage = Civi::settings()->get('search_autocomplete_count');
111 if (isset($request['params']) && isset($apiDefaults['params'])) {
112 $request['params'] += $apiDefaults['params'];
113 }
114 $request += $apiDefaults + $defaults;
115 // Default api params
116 $params = [
117 'sequential' => 1,
118 'options' => [],
119 ];
120 // When searching e.g. autocomplete
121 if ($request['input']) {
122 $params[$request['search_field']] = ['LIKE' => ($request['add_wildcard'] ? '%' : '') . $request['input'] . '%'];
123 }
124 // When looking up a field e.g. displaying existing record
125 if (!empty($request['id'])) {
126 if (is_string($request['id']) && strpos($request['id'], ',')) {
127 $request['id'] = explode(',', trim($request['id'], ', '));
128 }
129 // Don't run into search limits when prefilling selection
130 $params['options']['limit'] = NULL;
131 unset($params['options']['offset'], $request['params']['options']['limit'], $request['params']['options']['offset']);
132 $params[$request['id_field']] = is_array($request['id']) ? ['IN' => $request['id']] : $request['id'];
133 }
134 $request['params'] += $params;
135
136 $request['params']['options'] += [
137 // Add pagination parameters
138 'sort' => $request['label_field'],
139 // Adding one extra result allows us to see if there are any more
140 'limit' => $resultsPerPage + 1,
141 // Because sql is zero-based
142 'offset' => ($request['page_num'] - 1) * $resultsPerPage,
143 ];
144 }
145
146 /**
147 * Fallback implementation of getlist_params. May be overridden by individual apis.
148 *
149 * @param array $request
150 */
151 function _civicrm_api3_generic_getlist_params(&$request) {
152 $fieldsToReturn = [$request['id_field'], $request['label_field']];
153 if (!empty($request['image_field'])) {
154 $fieldsToReturn[] = $request['image_field'];
155 }
156 if (!empty($request['color_field'])) {
157 $fieldsToReturn[] = $request['color_field'];
158 }
159 if (!empty($request['description_field'])) {
160 $fieldsToReturn = array_merge($fieldsToReturn, (array) $request['description_field']);
161 }
162 $request['params']['return'] = array_unique(array_merge($fieldsToReturn, $request['extra']));
163 }
164
165 /**
166 * Fallback implementation of getlist_output. May be overridden by individual api functions.
167 *
168 * @param array $result
169 * @param array $request
170 * @param string $entity
171 * @param array $fields
172 *
173 * @return array
174 */
175 function _civicrm_api3_generic_getlist_output($result, $request, $entity, $fields) {
176 $output = [];
177 if (!empty($result['values'])) {
178 foreach ($result['values'] as $row) {
179 $data = [
180 'id' => $row[$request['id_field']],
181 'label' => $row[$request['label_field']],
182 ];
183 if (!empty($request['description_field'])) {
184 $data['description'] = [];
185 foreach ((array) $request['description_field'] as $field) {
186 if (!empty($row[$field])) {
187 if (!isset($fields[$field]['pseudoconstant'])) {
188 $data['description'][] = $row[$field];
189 }
190 else {
191 $data['description'][] = CRM_Core_PseudoConstant::getLabel(
192 _civicrm_api3_get_BAO($entity),
193 $field,
194 $row[$field]
195 );
196 }
197 }
198 }
199 };
200 if (!empty($request['image_field'])) {
201 $data['image'] = isset($row[$request['image_field']]) ? $row[$request['image_field']] : '';
202 }
203 if (isset($row[$request['color_field']])) {
204 $data['color'] = $row[$request['color_field']];
205 }
206 $output[] = $data;
207 }
208 }
209 return $output;
210 }
211
212 /**
213 * Common postprocess for getlist output
214 *
215 * @param $result
216 * @param $request
217 * @param $values
218 */
219 function _civicrm_api3_generic_getlist_postprocess($result, $request, &$values) {
220 $chains = [];
221 foreach ($request['params'] as $field => $param) {
222 if (substr($field, 0, 4) === 'api.') {
223 $chains[] = $field;
224 }
225 }
226 if (!empty($result['values'])) {
227 foreach (array_values($result['values']) as $num => $row) {
228 foreach ($request['extra'] as $field) {
229 $values[$num]['extra'][$field] = isset($row[$field]) ? $row[$field] : NULL;
230 }
231 foreach ($chains as $chain) {
232 $values[$num][$chain] = isset($row[$chain]) ? $row[$chain] : NULL;
233 }
234 }
235 }
236 }
237
238 /**
239 * Provide metadata for this api
240 *
241 * @param array $params
242 * @param array $apiRequest
243 */
244 function _civicrm_api3_generic_getlist_spec(&$params, $apiRequest) {
245 $params += [
246 'page_num' => [
247 'title' => 'Page Number',
248 'description' => "Current page of a multi-page lookup",
249 'type' => CRM_Utils_Type::T_INT,
250 ],
251 'input' => [
252 'title' => 'Search Input',
253 'description' => "String to search on",
254 'type' => CRM_Utils_Type::T_TEXT,
255 ],
256 'params' => [
257 'title' => 'API Params',
258 'description' => "Additional filters to send to the {$apiRequest['entity']} API.",
259 ],
260 'extra' => [
261 'title' => 'Extra',
262 'description' => 'Array of additional fields to return.',
263 ],
264 'image_field' => [
265 'title' => 'Image Field',
266 'description' => "Field that this entity uses to store icons (usually automatic)",
267 'type' => CRM_Utils_Type::T_TEXT,
268 ],
269 'id_field' => [
270 'title' => 'ID Field',
271 'description' => "Field that uniquely identifies this entity (usually automatic)",
272 'type' => CRM_Utils_Type::T_TEXT,
273 ],
274 'description_field' => [
275 'title' => 'Description Field',
276 'description' => "Field that this entity uses to store summary text (usually automatic)",
277 'type' => CRM_Utils_Type::T_TEXT,
278 ],
279 'label_field' => [
280 'title' => 'Label Field',
281 'description' => "Field to display as title of results (usually automatic)",
282 'type' => CRM_Utils_Type::T_TEXT,
283 ],
284 'search_field' => [
285 'title' => 'Search Field',
286 'description' => "Field to search on (assumed to be the same as label field unless otherwise specified)",
287 'type' => CRM_Utils_Type::T_TEXT,
288 ],
289 ];
290 }