Commit | Line | Data |
---|---|---|
6a488035 | 1 | <?php |
6a488035 | 2 | /* |
a30c801b TO |
3 | +--------------------------------------------------------------------+ |
4 | | Copyright CiviCRM LLC. All rights reserved. | | |
5 | | | | |
6 | | This work is published under the GNU AGPLv3 license with some | | |
7 | | permitted exceptions and without any warranty. For full license | | |
8 | | and copyright information, see https://civicrm.org/licensing | | |
9 | +--------------------------------------------------------------------+ | |
e70a7fc0 | 10 | */ |
6a488035 TO |
11 | |
12 | /** | |
b081365f | 13 | * CiviCRM APIv3 utility functions. |
6a488035 TO |
14 | * |
15 | * @package CiviCRM_APIv3 | |
6a488035 TO |
16 | */ |
17 | ||
18 | /** | |
61fe4988 | 19 | * Initialize CiviCRM - should be run at the start of each API function. |
6a488035 TO |
20 | */ |
21 | function _civicrm_api3_initialize() { | |
22fd1690 ARW |
22 | require_once 'CRM/Core/ClassLoader.php'; |
23 | CRM_Core_ClassLoader::singleton()->register(); | |
24 | CRM_Core_Config::singleton(); | |
25 | } | |
6a488035 | 26 | |
11e09c59 | 27 | /** |
61fe4988 | 28 | * Wrapper Function for civicrm_verify_mandatory to make it simple to pass either / or fields for checking. |
6a488035 | 29 | * |
cf470720 TO |
30 | * @param array $params |
31 | * Array of fields to check. | |
32 | * @param array $daoName | |
33 | * String DAO to check for required fields (create functions only). | |
34 | * @param array $keyoptions | |
35 | * List of required fields options. One of the options is required. | |
a22a5119 | 36 | * |
37 | * @throws \API_Exception | |
6a488035 | 38 | */ |
cf8f0fff CW |
39 | function civicrm_api3_verify_one_mandatory($params, $daoName = NULL, $keyoptions = []) { |
40 | $keys = [[]]; | |
6a488035 TO |
41 | foreach ($keyoptions as $key) { |
42 | $keys[0][] = $key; | |
43 | } | |
44 | civicrm_api3_verify_mandatory($params, $daoName, $keys); | |
45 | } | |
46 | ||
11e09c59 | 47 | /** |
61fe4988 | 48 | * Check mandatory fields are included. |
6a488035 | 49 | * |
cf470720 TO |
50 | * @param array $params |
51 | * Array of fields to check. | |
52 | * @param array $daoName | |
53 | * String DAO to check for required fields (create functions only). | |
54 | * @param array $keys | |
55 | * List of required fields. A value can be an array denoting that either this or that is required. | |
6a488035 | 56 | * @param bool $verifyDAO |
cd5823ae EM |
57 | * |
58 | * @throws \API_Exception | |
6a488035 | 59 | */ |
cf8f0fff CW |
60 | function civicrm_api3_verify_mandatory($params, $daoName = NULL, $keys = [], $verifyDAO = TRUE) { |
61 | $unmatched = []; | |
6a488035 TO |
62 | |
63 | if (!empty($params['id'])) { | |
cf8f0fff | 64 | $keys = ['version']; |
6a488035 TO |
65 | } |
66 | else { | |
67 | if (!in_array('version', $keys)) { | |
68 | // required from v3 onwards | |
69 | $keys[] = 'version'; | |
70 | } | |
71 | } | |
72 | foreach ($keys as $key) { | |
73 | if (is_array($key)) { | |
74 | $match = 0; | |
cf8f0fff | 75 | $optionset = []; |
6a488035 TO |
76 | foreach ($key as $subkey) { |
77 | if (!array_key_exists($subkey, $params) || empty($params[$subkey])) { | |
78 | $optionset[] = $subkey; | |
79 | } | |
80 | else { | |
210737b6 | 81 | // As long as there is one match we don't need to return anything. |
6a488035 TO |
82 | $match = 1; |
83 | } | |
84 | } | |
85 | if (empty($match) && !empty($optionset)) { | |
86 | $unmatched[] = "one of (" . implode(", ", $optionset) . ")"; | |
87 | } | |
88 | } | |
89 | else { | |
5ba3bfc8 | 90 | // Disallow empty values except for the number zero. |
210737b6 | 91 | // TODO: create a utility for this since it's needed in many places. |
5ba3bfc8 | 92 | if (!array_key_exists($key, $params) || (empty($params[$key]) && $params[$key] !== 0 && $params[$key] !== '0')) { |
6a488035 TO |
93 | $unmatched[] = $key; |
94 | } | |
95 | } | |
96 | } | |
97 | if (!empty($unmatched)) { | |
a22a5119 | 98 | throw new API_Exception('Mandatory key(s) missing from params array: ' . implode(", ", $unmatched), 'mandatory_missing', ["fields" => $unmatched]); |
6a488035 TO |
99 | } |
100 | } | |
101 | ||
102 | /** | |
61fe4988 | 103 | * Create error array. |
6a488035 | 104 | * |
61fe4988 | 105 | * @param string $msg |
916b48b6 | 106 | * @param array $data |
61fe4988 | 107 | * |
a6c01b45 | 108 | * @return array |
6a488035 | 109 | */ |
cf8f0fff | 110 | function civicrm_api3_create_error($msg, $data = []) { |
6a488035 TO |
111 | $data['is_error'] = 1; |
112 | $data['error_message'] = $msg; | |
2deb3dbe | 113 | |
9c465c3b TO |
114 | // we will show sql to privileged user only (not sure of a specific |
115 | // security hole here but seems sensible - perhaps should apply to the trace as well?) | |
8919965f | 116 | if (isset($data['sql'])) { |
a22a5119 | 117 | if (CRM_Core_Permission::check('Administer CiviCRM') || CIVICRM_UF === 'UnitTests') { |
8919965f ML |
118 | // Isn't this redundant? |
119 | $data['debug_information'] = $data['sql']; | |
120 | } | |
121 | else { | |
122 | unset($data['sql']); | |
123 | } | |
e7c4a581 | 124 | } |
6a488035 TO |
125 | return $data; |
126 | } | |
127 | ||
128 | /** | |
35823763 | 129 | * Format array in result output style. |
6a488035 | 130 | * |
77b97be7 | 131 | * @param array|int $values values generated by API operation (the result) |
cf470720 TO |
132 | * @param array $params |
133 | * Parameters passed into API call. | |
134 | * @param string $entity | |
135 | * The entity being acted on. | |
136 | * @param string $action | |
137 | * The action passed to the API. | |
138 | * @param object $dao | |
139 | * DAO object to be freed here. | |
140 | * @param array $extraReturnValues | |
141 | * Additional values to be added to top level of result array(. | |
6a488035 TO |
142 | * - this param is currently used for legacy behaviour support |
143 | * | |
a6c01b45 | 144 | * @return array |
a22a5119 | 145 | * @throws \CiviCRM_API3_Exception |
6a488035 | 146 | */ |
cf8f0fff CW |
147 | function civicrm_api3_create_success($values = 1, $params = [], $entity = NULL, $action = NULL, &$dao = NULL, $extraReturnValues = []) { |
148 | $result = []; | |
4846df91 CW |
149 | $lowercase_entity = _civicrm_api_get_entity_name_from_camel($entity); |
150 | // TODO: This shouldn't be necessary but this fn sometimes gets called with lowercase entity | |
151 | $entity = _civicrm_api_get_camel_name($entity); | |
6a488035 TO |
152 | $result['is_error'] = 0; |
153 | //lets set the ['id'] field if it's not set & we know what the entity is | |
a22a5119 | 154 | if (is_array($values) && $entity && $action !== 'getfields') { |
6a488035 | 155 | foreach ($values as $key => $item) { |
a22a5119 | 156 | if (empty($item['id']) && !empty($item[$lowercase_entity . '_id'])) { |
157 | $values[$key]['id'] = $item[$lowercase_entity . '_id']; | |
6a488035 | 158 | } |
9b873358 | 159 | if (!empty($item['financial_type_id'])) { |
258c92c6 SL |
160 | // 4.3 legacy handling. |
161 | $values[$key]['contribution_type_id'] = $item['financial_type_id']; | |
a1c68fd2 | 162 | } |
6e7cc0f5 SL |
163 | if (!empty($item['contribution_cancel_date'])) { |
164 | // 5.16 legacy handling. | |
165 | $values[$key]['cancel_date'] = $item['contribution_cancel_date']; | |
166 | } | |
9b873358 | 167 | if (!empty($item['next_sched_contribution_date'])) { |
797b807e | 168 | // 4.4 legacy handling |
169 | $values[$key]['next_sched_contribution'] = $item['next_sched_contribution_date']; | |
170 | } | |
6a488035 TO |
171 | } |
172 | } | |
d8453bed | 173 | |
080b7aca | 174 | if (is_array($params) && $entity && !empty($params['debug'])) { |
a22a5119 | 175 | if (is_string($action) && $action !== 'getfields') { |
cf8f0fff | 176 | $apiFields = civicrm_api($entity, 'getfields', ['version' => 3, 'action' => $action] + $params); |
6a488035 | 177 | } |
a22a5119 | 178 | elseif ($action !== 'getfields') { |
cf8f0fff | 179 | $apiFields = civicrm_api($entity, 'getfields', ['version' => 3] + $params); |
6a488035 TO |
180 | } |
181 | else { | |
182 | $apiFields = FALSE; | |
183 | } | |
184 | ||
cf8f0fff | 185 | $allFields = []; |
a22a5119 | 186 | if ($action !== 'getfields' && is_array($apiFields) && is_array(CRM_Utils_Array::value('values', $apiFields))) { |
6a488035 TO |
187 | $allFields = array_keys($apiFields['values']); |
188 | } | |
189 | $paramFields = array_keys($params); | |
cf8f0fff | 190 | $undefined = array_diff($paramFields, $allFields, array_keys($_COOKIE), [ |
9d32e6f7 EM |
191 | 'action', |
192 | 'entity', | |
193 | 'debug', | |
194 | 'version', | |
195 | 'check_permissions', | |
196 | 'IDS_request_uri', | |
197 | 'IDS_user_agent', | |
198 | 'return', | |
199 | 'sequential', | |
200 | 'rowCount', | |
201 | 'option_offset', | |
202 | 'option_limit', | |
203 | 'custom', | |
204 | 'option_sort', | |
205 | 'options', | |
206 | 'prettyprint', | |
7c31ae57 | 207 | ]); |
6a488035 TO |
208 | if ($undefined) { |
209 | $result['undefined_fields'] = array_merge($undefined); | |
210 | } | |
211 | } | |
6a488035 TO |
212 | |
213 | $result['version'] = 3; | |
214 | if (is_array($values)) { | |
e7c4a581 | 215 | $result['count'] = (int) count($values); |
6a488035 TO |
216 | |
217 | // Convert value-separated strings to array | |
a22a5119 | 218 | if ($action !== 'getfields') { |
72b05357 | 219 | _civicrm_api3_separate_values($values); |
220 | } | |
6a488035 TO |
221 | |
222 | if ($result['count'] == 1) { | |
223 | list($result['id']) = array_keys($values); | |
224 | } | |
225 | elseif (!empty($values['id']) && is_int($values['id'])) { | |
226 | $result['id'] = $values['id']; | |
227 | } | |
228 | } | |
229 | else { | |
230 | $result['count'] = !empty($values) ? 1 : 0; | |
231 | } | |
232 | ||
233 | if (is_array($values) && isset($params['sequential']) && | |
234 | $params['sequential'] == 1 | |
235 | ) { | |
236 | $result['values'] = array_values($values); | |
237 | } | |
238 | else { | |
239 | $result['values'] = $values; | |
240 | } | |
22e263ad | 241 | if (!empty($params['options']['metadata'])) { |
9d32e6f7 | 242 | // We've made metadata an array but only supporting 'fields' atm. |
22e263ad | 243 | if (in_array('fields', (array) $params['options']['metadata']) && $action !== 'getfields') { |
cf8f0fff | 244 | $fields = civicrm_api3($entity, 'getfields', [ |
9d32e6f7 | 245 | 'action' => substr($action, 0, 3) == 'get' ? 'get' : 'create', |
cf8f0fff | 246 | ]); |
dc5a7701 E |
247 | $result['metadata']['fields'] = $fields['values']; |
248 | } | |
249 | } | |
9d32e6f7 | 250 | // Report deprecations. |
a14e9d08 | 251 | $deprecated = _civicrm_api3_deprecation_check($entity, $result); |
1726c7d2 | 252 | // Always report "setvalue" action as deprecated. |
a22a5119 | 253 | if (!is_string($deprecated) && ($action === 'getactions' || $action === 'setvalue')) { |
cf8f0fff | 254 | $deprecated = ((array) $deprecated) + ['setvalue' => 'The "setvalue" action is deprecated. Use "create" with an id instead.']; |
265df5a0 | 255 | } |
9d32e6f7 | 256 | // Always report "update" action as deprecated. |
a22a5119 | 257 | if (!is_string($deprecated) && ($action === 'getactions' || $action === 'update')) { |
cf8f0fff | 258 | $deprecated = ((array) $deprecated) + ['update' => 'The "update" action is deprecated. Use "create" with an id instead.']; |
a14e9d08 CW |
259 | } |
260 | if ($deprecated) { | |
9d32e6f7 | 261 | // Metadata-level deprecations or wholesale entity deprecations. |
a22a5119 | 262 | if ($entity === 'Entity' || $action === 'getactions' || is_string($deprecated)) { |
a14e9d08 CW |
263 | $result['deprecated'] = $deprecated; |
264 | } | |
265 | // Action-specific deprecations | |
266 | elseif (!empty($deprecated[$action])) { | |
267 | $result['deprecated'] = $deprecated[$action]; | |
268 | } | |
269 | } | |
6a488035 TO |
270 | return array_merge($result, $extraReturnValues); |
271 | } | |
11e09c59 TO |
272 | |
273 | /** | |
61fe4988 EM |
274 | * Load the DAO of the entity. |
275 | * | |
645ee340 | 276 | * @param $entity |
9d32e6f7 | 277 | * |
645ee340 | 278 | * @return bool |
6a488035 TO |
279 | */ |
280 | function _civicrm_api3_load_DAO($entity) { | |
281 | $dao = _civicrm_api3_get_DAO($entity); | |
282 | if (empty($dao)) { | |
283 | return FALSE; | |
284 | } | |
6a488035 TO |
285 | $d = new $dao(); |
286 | return $d; | |
287 | } | |
11e09c59 TO |
288 | |
289 | /** | |
61fe4988 EM |
290 | * Return the DAO of the function or Entity. |
291 | * | |
cf470720 TO |
292 | * @param string $name |
293 | * Either a function of the api (civicrm_{entity}_create or the entity name. | |
16b10e64 CW |
294 | * return the DAO name to manipulate this function |
295 | * eg. "civicrm_api3_contact_create" or "Contact" will return "CRM_Contact_BAO_Contact" | |
61fe4988 | 296 | * |
26728d3f | 297 | * @return mixed|string |
6a488035 TO |
298 | */ |
299 | function _civicrm_api3_get_DAO($name) { | |
6a488035 TO |
300 | if (strpos($name, 'civicrm_api3') !== FALSE) { |
301 | $last = strrpos($name, '_'); | |
302 | // len ('civicrm_api3_') == 13 | |
303 | $name = substr($name, 13, $last - 13); | |
304 | } | |
305 | ||
1644b908 | 306 | $name = _civicrm_api_get_camel_name($name); |
6a488035 | 307 | |
a22a5119 | 308 | if ($name === 'Individual' || $name === 'Household' || $name === 'Organization') { |
6a488035 TO |
309 | $name = 'Contact'; |
310 | } | |
311 | ||
da54ec85 CW |
312 | // hack to deal with incorrectly named BAO/DAO - see CRM-10859 |
313 | ||
bd6658bd | 314 | // FIXME: DAO should be renamed CRM_Mailing_DAO_MailingEventQueue |
a22a5119 | 315 | if ($name === 'MailingEventQueue') { |
bd6658bd TO |
316 | return 'CRM_Mailing_Event_DAO_Queue'; |
317 | } | |
da54ec85 CW |
318 | // FIXME: DAO should be renamed CRM_Mailing_DAO_MailingRecipients |
319 | // but am not confident mailing_recipients is tested so have not tackled. | |
a22a5119 | 320 | if ($name === 'MailingRecipients') { |
da54ec85 | 321 | return 'CRM_Mailing_DAO_Recipients'; |
6a488035 | 322 | } |
da54ec85 | 323 | // FIXME: DAO should be renamed CRM_ACL_DAO_AclRole |
a22a5119 | 324 | if ($name === 'AclRole') { |
663072a5 CW |
325 | return 'CRM_ACL_DAO_EntityRole'; |
326 | } | |
da54ec85 CW |
327 | // FIXME: DAO should be renamed CRM_SMS_DAO_SmsProvider |
328 | // But this would impact SMS extensions so need to coordinate | |
329 | // Probably best approach is to migrate them to use the api and decouple them from core BAOs | |
a22a5119 | 330 | if ($name === 'SmsProvider') { |
da54ec85 CW |
331 | return 'CRM_SMS_DAO_Provider'; |
332 | } | |
333 | // FIXME: DAO names should follow CamelCase convention | |
a22a5119 | 334 | if ($name === 'Im' || $name === 'Acl' || $name === 'Pcp') { |
1fe97a01 | 335 | $name = strtoupper($name); |
6a488035 | 336 | } |
23474ab3 | 337 | $dao = CRM_Core_DAO_AllCoreTables::getFullName($name); |
9537a4e1 | 338 | if ($dao || !$name) { |
23474ab3 CW |
339 | return $dao; |
340 | } | |
341 | ||
342 | // Really weird apis can declare their own DAO name. Not sure if this is a good idea... | |
22e263ad | 343 | if (file_exists("api/v3/$name.php")) { |
db47ea7b | 344 | include_once "api/v3/$name.php"; |
345 | } | |
bada0f66 | 346 | |
a22a5119 | 347 | $daoFn = '_civicrm_api3_' . _civicrm_api_get_entity_name_from_camel($name) . '_DAO'; |
23474ab3 CW |
348 | if (function_exists($daoFn)) { |
349 | return $daoFn(); | |
350 | } | |
351 | ||
352 | return NULL; | |
6a488035 TO |
353 | } |
354 | ||
11e09c59 | 355 | /** |
0b80f0b4 | 356 | * Return the BAO name of the function or Entity. |
61fe4988 | 357 | * |
cf470720 TO |
358 | * @param string $name |
359 | * Is either a function of the api (civicrm_{entity}_create or the entity name. | |
16b10e64 CW |
360 | * return the DAO name to manipulate this function |
361 | * eg. "civicrm_contact_create" or "Contact" will return "CRM_Contact_BAO_Contact" | |
61fe4988 | 362 | * |
8bcc0d86 | 363 | * @return string|null |
6a488035 TO |
364 | */ |
365 | function _civicrm_api3_get_BAO($name) { | |
da54ec85 | 366 | // FIXME: DAO should be renamed CRM_Badge_DAO_BadgeLayout |
a22a5119 | 367 | if ($name === 'PrintLabel') { |
da54ec85 CW |
368 | return 'CRM_Badge_BAO_Layout'; |
369 | } | |
785f03e2 | 370 | if ($name === 'Order') { |
371 | // Order basically maps to contribution at the top level but | |
372 | // has enhanced access to other entities. | |
373 | $name = 'Contribution'; | |
374 | } | |
e13fa54b | 375 | if ($name === 'Dedupe') { |
376 | // Dedupe is a pseudoentity for PrevNextCache - but accessing dedupe related info | |
377 | // not the other cache info like search results (which could in fact be in Redis or another cache engine) | |
378 | $name = 'PrevNextCache'; | |
379 | } | |
a494d7a3 | 380 | if ($name === 'Payment') { |
381 | $name = 'FinancialTrxn'; | |
382 | } | |
6a488035 | 383 | $dao = _civicrm_api3_get_DAO($name); |
5c1174d3 CW |
384 | if (!$dao) { |
385 | return NULL; | |
386 | } | |
d9f036bb | 387 | $bao = str_replace("DAO", "BAO", $dao); |
49e101d0 | 388 | $file = strtr($bao, '_', '/') . '.php'; |
5c1174d3 | 389 | // Check if this entity actually has a BAO. Fall back on the DAO if not. |
49e101d0 | 390 | return stream_resolve_include_path($file) ? $bao : $dao; |
6a488035 TO |
391 | } |
392 | ||
393 | /** | |
61fe4988 EM |
394 | * Recursive function to explode value-separated strings into arrays. |
395 | * | |
645ee340 | 396 | * @param $values |
6a488035 TO |
397 | */ |
398 | function _civicrm_api3_separate_values(&$values) { | |
399 | $sp = CRM_Core_DAO::VALUE_SEPARATOR; | |
400 | foreach ($values as $key => & $value) { | |
401 | if (is_array($value)) { | |
402 | _civicrm_api3_separate_values($value); | |
403 | } | |
404 | elseif (is_string($value)) { | |
61fe4988 | 405 | // This is to honor the way case API was originally written. |
a22a5119 | 406 | if ($key === 'case_type_id') { |
6a488035 TO |
407 | $value = trim(str_replace($sp, ',', $value), ','); |
408 | } | |
409 | elseif (strpos($value, $sp) !== FALSE) { | |
410 | $value = explode($sp, trim($value, $sp)); | |
411 | } | |
412 | } | |
413 | } | |
414 | } | |
11e09c59 TO |
415 | |
416 | /** | |
61fe4988 EM |
417 | * This is a legacy wrapper for api_store_values. |
418 | * | |
419 | * It checks suitable fields using getfields rather than DAO->fields. | |
6a488035 | 420 | * |
61fe4988 | 421 | * Getfields has handling for how to deal with unique names which dao->fields doesn't |
6a488035 TO |
422 | * |
423 | * Note this is used by BAO type create functions - eg. contribution | |
61fe4988 | 424 | * |
6a488035 TO |
425 | * @param string $entity |
426 | * @param array $params | |
427 | * @param array $values | |
428 | */ | |
9b873358 | 429 | function _civicrm_api3_filter_fields_for_bao($entity, &$params, &$values) { |
cf8f0fff | 430 | $fields = civicrm_api($entity, 'getfields', ['version' => 3, 'action' => 'create']); |
6a488035 TO |
431 | $fields = $fields['values']; |
432 | _civicrm_api3_store_values($fields, $params, $values); | |
433 | } | |
7c31ae57 | 434 | |
6a488035 | 435 | /** |
61fe4988 | 436 | * Store values. |
6a488035 TO |
437 | * |
438 | * @param array $fields | |
439 | * @param array $params | |
440 | * @param array $values | |
441 | * | |
a6c01b45 | 442 | * @return Bool |
6a488035 TO |
443 | */ |
444 | function _civicrm_api3_store_values(&$fields, &$params, &$values) { | |
445 | $valueFound = FALSE; | |
446 | ||
447 | $keys = array_intersect_key($params, $fields); | |
448 | foreach ($keys as $name => $value) { | |
449 | if ($name !== 'id') { | |
450 | $values[$name] = $value; | |
451 | $valueFound = TRUE; | |
452 | } | |
453 | } | |
454 | return $valueFound; | |
455 | } | |
26728d3f | 456 | |
836231f4 JV |
457 | /** |
458 | * Returns field names of the given entity fields. | |
459 | * | |
2b28667f | 460 | * @param array $fields |
836231f4 JV |
461 | * Fields array to retrieve the field names for. |
462 | * @return array | |
463 | */ | |
464 | function _civicrm_api3_field_names($fields) { | |
cf8f0fff | 465 | $result = []; |
84c546ab | 466 | foreach ($fields as $key => $value) { |
a50d9fb1 | 467 | if (!empty($value['name'])) { |
84c546ab | 468 | $result[] = $value['name']; |
a50d9fb1 | 469 | } |
836231f4 JV |
470 | } |
471 | return $result; | |
472 | } | |
473 | ||
6a488035 | 474 | /** |
61fe4988 EM |
475 | * Get function for query object api. |
476 | * | |
477 | * The API supports 2 types of get request. The more complex uses the BAO query object. | |
6a488035 TO |
478 | * This is a generic function for those functions that call it |
479 | * | |
480 | * At the moment only called by contact we should extend to contribution & | |
481 | * others that use the query object. Note that this function passes permission information in. | |
482 | * The others don't | |
483 | * | |
c23f45d3 | 484 | * Ideally this would be merged with _civicrm_get_query_object but we need to resolve differences in what the |
82f7d8b2 | 485 | * 2 variants call |
61fe4988 | 486 | * |
26728d3f | 487 | * @param $entity |
cf470720 TO |
488 | * @param array $params |
489 | * As passed into api get or getcount function. | |
490 | * @param array $additional_options | |
491 | * Array of options (so we can modify the filter). | |
492 | * @param bool $getCount | |
493 | * Are we just after the count. | |
9ae25b56 | 494 | * @param int $mode |
495 | * This basically correlates to the component. | |
f12e4c41 | 496 | * @param null|array $defaultReturnProperties |
497 | * Default return properties for the entity | |
498 | * (used if return not set - but don't do that - set return!). | |
26728d3f | 499 | * |
2241036a | 500 | * @return array |
f12e4c41 | 501 | * @throws API_Exception |
6a488035 | 502 | */ |
cf8f0fff | 503 | function _civicrm_api3_get_using_query_object($entity, $params, $additional_options = [], $getCount = NULL, $mode = 1, $defaultReturnProperties = NULL) { |
244bbdd8 | 504 | $lowercase_entity = _civicrm_api_get_entity_name_from_camel($entity); |
6a488035 | 505 | // Convert id to e.g. contact_id |
244bbdd8 CW |
506 | if (empty($params[$lowercase_entity . '_id']) && isset($params['id'])) { |
507 | $params[$lowercase_entity . '_id'] = $params['id']; | |
6a488035 TO |
508 | } |
509 | unset($params['id']); | |
510 | ||
511 | $options = _civicrm_api3_get_options_from_params($params, TRUE); | |
512 | ||
513 | $inputParams = array_merge( | |
cf8f0fff CW |
514 | CRM_Utils_Array::value('input_params', $options, []), |
515 | CRM_Utils_Array::value('input_params', $additional_options, []) | |
6a488035 TO |
516 | ); |
517 | $returnProperties = array_merge( | |
cf8f0fff CW |
518 | CRM_Utils_Array::value('return', $options, []), |
519 | CRM_Utils_Array::value('return', $additional_options, []) | |
6a488035 | 520 | ); |
9b873358 | 521 | if (empty($returnProperties)) { |
9ae25b56 | 522 | $returnProperties = $defaultReturnProperties; |
6a488035 | 523 | } |
9b873358 | 524 | if (!empty($params['check_permissions'])) { |
6a488035 | 525 | // we will filter query object against getfields |
cf8f0fff | 526 | $fields = civicrm_api($entity, 'getfields', ['version' => 3, 'action' => 'get']); |
6a488035 | 527 | // we need to add this in as earlier in this function 'id' was unset in favour of $entity_id |
cf8f0fff CW |
528 | $fields['values'][$lowercase_entity . '_id'] = []; |
529 | $varsToFilter = ['returnProperties', 'inputParams']; | |
9b873358 TO |
530 | foreach ($varsToFilter as $varToFilter) { |
531 | if (!is_array($$varToFilter)) { | |
6a488035 TO |
532 | continue; |
533 | } | |
534 | //I was going to throw an exception rather than silently filter out - but | |
535 | //would need to diff out of exceptions arr other keys like 'options', 'return', 'api. etcetc | |
536 | //so we are silently ignoring parts of their request | |
537 | //$exceptionsArr = array_diff(array_keys($$varToFilter), array_keys($fields['values'])); | |
538 | $$varToFilter = array_intersect_key($$varToFilter, $fields['values']); | |
539 | } | |
540 | } | |
35671d00 | 541 | $options = array_merge($options, $additional_options); |
6a488035 TO |
542 | $sort = CRM_Utils_Array::value('sort', $options, NULL); |
543 | $offset = CRM_Utils_Array::value('offset', $options, NULL); | |
544 | $limit = CRM_Utils_Array::value('limit', $options, NULL); | |
545 | $smartGroupCache = CRM_Utils_Array::value('smartGroupCache', $params); | |
546 | ||
9b873358 | 547 | if ($getCount) { |
6a488035 TO |
548 | $limit = NULL; |
549 | $returnProperties = NULL; | |
550 | } | |
551 | ||
abb4c597 | 552 | if (substr($sort, 0, 2) == 'id') { |
244bbdd8 | 553 | $sort = $lowercase_entity . "_" . $sort; |
abb4c597 | 554 | } |
555 | ||
6a488035 | 556 | $newParams = CRM_Contact_BAO_Query::convertFormValues($inputParams); |
d031c654 | 557 | |
35671d00 | 558 | $skipPermissions = !empty($params['check_permissions']) ? 0 : 1; |
78c0bfc0 | 559 | |
9ae25b56 | 560 | list($entities) = CRM_Contact_BAO_Query::apiQuery( |
6a488035 TO |
561 | $newParams, |
562 | $returnProperties, | |
563 | NULL, | |
564 | $sort, | |
35671d00 | 565 | $offset, |
6a488035 TO |
566 | $limit, |
567 | $smartGroupCache, | |
568 | $getCount, | |
9ae25b56 | 569 | $skipPermissions, |
66670e4d | 570 | $mode, |
0606198b | 571 | $entity, |
572 | TRUE | |
6a488035 | 573 | ); |
6a488035 TO |
574 | |
575 | return $entities; | |
576 | } | |
11e09c59 | 577 | |
82f7d8b2 | 578 | /** |
61fe4988 EM |
579 | * Get dao query object based on input params. |
580 | * | |
82f7d8b2 EM |
581 | * Ideally this would be merged with _civicrm_get_using_query_object but we need to resolve differences in what the |
582 | * 2 variants call | |
583 | * | |
584 | * @param array $params | |
585 | * @param string $mode | |
586 | * @param string $entity | |
61fe4988 | 587 | * |
971d41b1 CW |
588 | * @return array |
589 | * [CRM_Core_DAO|CRM_Contact_BAO_Query] | |
82f7d8b2 EM |
590 | */ |
591 | function _civicrm_api3_get_query_object($params, $mode, $entity) { | |
971d41b1 CW |
592 | $options = _civicrm_api3_get_options_from_params($params, TRUE, $entity, 'get'); |
593 | $sort = CRM_Utils_Array::value('sort', $options, NULL); | |
594 | $offset = CRM_Utils_Array::value('offset', $options); | |
595 | $rowCount = CRM_Utils_Array::value('limit', $options); | |
cf8f0fff | 596 | $inputParams = CRM_Utils_Array::value('input_params', $options, []); |
82f7d8b2 EM |
597 | $returnProperties = CRM_Utils_Array::value('return', $options, NULL); |
598 | if (empty($returnProperties)) { | |
599 | $returnProperties = CRM_Contribute_BAO_Query::defaultReturnProperties($mode); | |
600 | } | |
601 | ||
3c151c70 | 602 | $newParams = CRM_Contact_BAO_Query::convertFormValues($inputParams, 0, FALSE, $entity); |
82f7d8b2 | 603 | $query = new CRM_Contact_BAO_Query($newParams, $returnProperties, NULL, |
835307a7 | 604 | FALSE, FALSE, $mode, |
0606198b | 605 | empty($params['check_permissions']), |
606 | TRUE, TRUE, NULL, 'AND', 'NULL', TRUE | |
82f7d8b2 EM |
607 | ); |
608 | list($select, $from, $where, $having) = $query->query(); | |
609 | ||
610 | $sql = "$select $from $where $having"; | |
611 | ||
612 | if (!empty($sort)) { | |
1217e5e6 | 613 | $sort = CRM_Utils_Type::escape($sort, 'MysqlOrderBy'); |
82f7d8b2 EM |
614 | $sql .= " ORDER BY $sort "; |
615 | } | |
22e263ad | 616 | if (!empty($rowCount)) { |
82f7d8b2 EM |
617 | $sql .= " LIMIT $offset, $rowCount "; |
618 | } | |
619 | $dao = CRM_Core_DAO::executeQuery($sql); | |
cf8f0fff | 620 | return [$dao, $query]; |
82f7d8b2 EM |
621 | } |
622 | ||
11e09c59 | 623 | /** |
61fe4988 EM |
624 | * Function transfers the filters being passed into the DAO onto the params object. |
625 | * | |
0298287b | 626 | * @deprecated DAO based retrieval is being phased out. |
627 | * | |
a75c13cc EM |
628 | * @param CRM_Core_DAO $dao |
629 | * @param array $params | |
630 | * @param bool $unique | |
0f3699bf | 631 | * @param array $extraSql |
632 | * API specific queries eg for event isCurrent would be converted to | |
633 | * $extraSql['where'] = array('civicrm_event' => array('(start_date >= CURDATE() || end_date >= CURDATE())')); | |
a75c13cc EM |
634 | * |
635 | * @throws API_Exception | |
636 | * @throws Exception | |
6a488035 | 637 | */ |
cf8f0fff | 638 | function _civicrm_api3_dao_set_filter(&$dao, $params, $unique = TRUE, $extraSql = []) { |
244bbdd8 CW |
639 | $entity = _civicrm_api_get_entity_name_from_dao($dao); |
640 | $lowercase_entity = _civicrm_api_get_entity_name_from_camel($entity); | |
641 | if (!empty($params[$lowercase_entity . "_id"]) && empty($params['id'])) { | |
6a488035 | 642 | //if entity_id is set then treat it as ID (will be overridden by id if set) |
244bbdd8 | 643 | $params['id'] = $params[$lowercase_entity . "_id"]; |
6a488035 | 644 | } |
461c9a60 EM |
645 | $allfields = _civicrm_api3_build_fields_array($dao, $unique); |
646 | $fields = array_intersect(array_keys($allfields), array_keys($params)); | |
3c70d501 | 647 | |
648 | $options = _civicrm_api3_get_options_from_params($params); | |
6a488035 TO |
649 | //apply options like sort |
650 | _civicrm_api3_apply_options_to_dao($params, $dao, $entity); | |
651 | ||
652 | //accept filters like filter.activity_date_time_high | |
653 | // std is now 'filters' => .. | |
654 | if (strstr(implode(',', array_keys($params)), 'filter')) { | |
655 | if (isset($params['filters']) && is_array($params['filters'])) { | |
656 | foreach ($params['filters'] as $paramkey => $paramvalue) { | |
657 | _civicrm_api3_apply_filters_to_dao($paramkey, $paramvalue, $dao); | |
658 | } | |
659 | } | |
660 | else { | |
661 | foreach ($params as $paramkey => $paramvalue) { | |
662 | if (strstr($paramkey, 'filter')) { | |
663 | _civicrm_api3_apply_filters_to_dao(substr($paramkey, 7), $paramvalue, $dao); | |
664 | } | |
665 | } | |
666 | } | |
667 | } | |
6a488035 | 668 | if (!$fields) { |
cf8f0fff | 669 | $fields = []; |
6a488035 TO |
670 | } |
671 | ||
672 | foreach ($fields as $field) { | |
673 | if (is_array($params[$field])) { | |
674 | //get the actual fieldname from db | |
675 | $fieldName = $allfields[$field]['name']; | |
a038992c | 676 | $where = CRM_Core_DAO::createSqlFilter($fieldName, $params[$field], 'String'); |
22e263ad | 677 | if (!empty($where)) { |
a038992c | 678 | $dao->whereAdd($where); |
6a488035 TO |
679 | } |
680 | } | |
681 | else { | |
682 | if ($unique) { | |
ed22af33 TO |
683 | $daoFieldName = $allfields[$field]['name']; |
684 | if (empty($daoFieldName)) { | |
685 | throw new API_Exception("Failed to determine field name for \"$field\""); | |
686 | } | |
687 | $dao->{$daoFieldName} = $params[$field]; | |
6a488035 TO |
688 | } |
689 | else { | |
690 | $dao->$field = $params[$field]; | |
691 | } | |
692 | } | |
693 | } | |
0f3699bf | 694 | if (!empty($extraSql['where'])) { |
695 | foreach ($extraSql['where'] as $table => $sqlWhere) { | |
696 | foreach ($sqlWhere as $where) { | |
697 | $dao->whereAdd($where); | |
698 | } | |
699 | } | |
700 | } | |
972322c5 | 701 | if (!empty($options['return']) && is_array($options['return']) && empty($options['is_count'])) { |
6a488035 | 702 | $dao->selectAdd(); |
9d32e6f7 EM |
703 | // Ensure 'id' is included. |
704 | $options['return']['id'] = TRUE; | |
35671d00 | 705 | $allfields = _civicrm_api3_get_unique_name_array($dao); |
3c70d501 | 706 | $returnMatched = array_intersect(array_keys($options['return']), $allfields); |
6a488035 | 707 | foreach ($returnMatched as $returnValue) { |
48e1c0dc | 708 | $dao->selectAdd($returnValue); |
6a488035 | 709 | } |
48e1c0dc | 710 | |
61fe4988 EM |
711 | // Not already matched on the field names. |
712 | $unmatchedFields = array_diff( | |
48e1c0dc | 713 | array_keys($options['return']), |
714 | $returnMatched | |
715 | ); | |
716 | ||
717 | $returnUniqueMatched = array_intersect( | |
718 | $unmatchedFields, | |
9d32e6f7 EM |
719 | // But a match for the field keys. |
720 | array_flip($allfields) | |
48e1c0dc | 721 | ); |
9b873358 | 722 | foreach ($returnUniqueMatched as $uniqueVal) { |
6a488035 | 723 | $dao->selectAdd($allfields[$uniqueVal]); |
6a488035 | 724 | } |
6a488035 | 725 | } |
6e1bb60c | 726 | $dao->setApiFilter($params); |
6a488035 TO |
727 | } |
728 | ||
11e09c59 | 729 | /** |
61fe4988 EM |
730 | * Apply filters (e.g. high, low) to DAO object (prior to find). |
731 | * | |
cf470720 TO |
732 | * @param string $filterField |
733 | * Field name of filter. | |
734 | * @param string $filterValue | |
735 | * Field value of filter. | |
736 | * @param object $dao | |
737 | * DAO object. | |
6a488035 TO |
738 | */ |
739 | function _civicrm_api3_apply_filters_to_dao($filterField, $filterValue, &$dao) { | |
740 | if (strstr($filterField, 'high')) { | |
741 | $fieldName = substr($filterField, 0, -5); | |
742 | $dao->whereAdd("($fieldName <= $filterValue )"); | |
743 | } | |
744 | if (strstr($filterField, 'low')) { | |
745 | $fieldName = substr($filterField, 0, -4); | |
746 | $dao->whereAdd("($fieldName >= $filterValue )"); | |
747 | } | |
9b873358 | 748 | if ($filterField == 'is_current' && $filterValue == 1) { |
6a488035 TO |
749 | $todayStart = date('Ymd000000', strtotime('now')); |
750 | $todayEnd = date('Ymd235959', strtotime('now')); | |
751 | $dao->whereAdd("(start_date <= '$todayStart' OR start_date IS NULL) AND (end_date >= '$todayEnd' OR end_date IS NULL)"); | |
9b873358 | 752 | if (property_exists($dao, 'is_active')) { |
6a488035 TO |
753 | $dao->whereAdd('is_active = 1'); |
754 | } | |
755 | } | |
756 | } | |
11e09c59 TO |
757 | |
758 | /** | |
6a488035 | 759 | * Get sort, limit etc options from the params - supporting old & new formats. |
9d32e6f7 EM |
760 | * |
761 | * Get returnProperties for legacy | |
26728d3f | 762 | * |
cf470720 TO |
763 | * @param array $params |
764 | * Params array as passed into civicrm_api. | |
765 | * @param bool $queryObject | |
9d32e6f7 | 766 | * Is this supporting a queryObject api (e.g contact) - if so we support more options. |
16b10e64 | 767 | * for legacy report & return a unique fields array |
26728d3f E |
768 | * |
769 | * @param string $entity | |
770 | * @param string $action | |
771 | * | |
1cfa04c4 | 772 | * @throws API_Exception |
a6c01b45 | 773 | * @return array |
72b3a70c | 774 | * options extracted from params |
6a488035 | 775 | */ |
d90b6399 | 776 | function _civicrm_api3_get_options_from_params($params, $queryObject = FALSE, $entity = '', $action = '') { |
4846df91 | 777 | $lowercase_entity = _civicrm_api_get_entity_name_from_camel($entity); |
972322c5 | 778 | $is_count = FALSE; |
6a488035 TO |
779 | $sort = CRM_Utils_Array::value('sort', $params, 0); |
780 | $sort = CRM_Utils_Array::value('option.sort', $params, $sort); | |
781 | $sort = CRM_Utils_Array::value('option_sort', $params, $sort); | |
782 | ||
783 | $offset = CRM_Utils_Array::value('offset', $params, 0); | |
784 | $offset = CRM_Utils_Array::value('option.offset', $params, $offset); | |
785 | // dear PHP thought it would be a good idea to transform a.b into a_b in the get/post | |
786 | $offset = CRM_Utils_Array::value('option_offset', $params, $offset); | |
787 | ||
788 | $limit = CRM_Utils_Array::value('rowCount', $params, 25); | |
789 | $limit = CRM_Utils_Array::value('option.limit', $params, $limit); | |
790 | $limit = CRM_Utils_Array::value('option_limit', $params, $limit); | |
791 | ||
792 | if (is_array(CRM_Utils_Array::value('options', $params))) { | |
972322c5 | 793 | // is count is set by generic getcount not user |
794 | $is_count = CRM_Utils_Array::value('is_count', $params['options']); | |
6a488035 TO |
795 | $offset = CRM_Utils_Array::value('offset', $params['options'], $offset); |
796 | $limit = CRM_Utils_Array::value('limit', $params['options'], $limit); | |
797 | $sort = CRM_Utils_Array::value('sort', $params['options'], $sort); | |
798 | } | |
799 | ||
cf8f0fff | 800 | $returnProperties = []; |
6a488035 TO |
801 | // handle the format return =sort_name,display_name... |
802 | if (array_key_exists('return', $params)) { | |
803 | if (is_array($params['return'])) { | |
804 | $returnProperties = array_fill_keys($params['return'], 1); | |
805 | } | |
806 | else { | |
807 | $returnProperties = explode(',', str_replace(' ', '', $params['return'])); | |
808 | $returnProperties = array_fill_keys($returnProperties, 1); | |
809 | } | |
810 | } | |
35671d00 | 811 | if ($entity && $action == 'get') { |
a7488080 | 812 | if (!empty($returnProperties['id'])) { |
4846df91 | 813 | $returnProperties[$lowercase_entity . '_id'] = 1; |
6a488035 TO |
814 | unset($returnProperties['id']); |
815 | } | |
6a488035 TO |
816 | } |
817 | ||
cf8f0fff | 818 | $options = [ |
ba93e7ad | 819 | 'offset' => CRM_Utils_Rule::integer($offset) ? $offset : NULL, |
7244a956 | 820 | 'limit' => (!$is_count && CRM_Utils_Rule::integer($limit)) ? $limit : NULL, |
6313f1f7 | 821 | 'is_count' => $is_count, |
cf8f0fff CW |
822 | 'return' => !empty($returnProperties) ? $returnProperties : [], |
823 | ]; | |
e9ab8548 | 824 | |
cf8f0fff | 825 | $finalSort = []; |
e9ab8548 | 826 | $options['sort'] = NULL; |
827 | if (!empty($sort)) { | |
4c6cc364 CW |
828 | if (!is_array($sort)) { |
829 | $sort = array_map('trim', explode(',', $sort)); | |
830 | } | |
831 | foreach ($sort as $s) { | |
a22a5119 | 832 | if ($s === '(1)' || CRM_Utils_Rule::mysqlOrderBy($s)) { |
833 | if ($entity && $action === 'get') { | |
8ff43f60 SL |
834 | switch (trim(strtolower($s))) { |
835 | case 'id': | |
836 | case 'id desc': | |
837 | case 'id asc': | |
838 | $s = str_replace('id', $lowercase_entity . '_id', $s); | |
839 | } | |
840 | } | |
1217e5e6 SL |
841 | $finalSort[] = $s; |
842 | } | |
843 | else { | |
844 | throw new API_Exception("Unknown field specified for sort. Cannot order by '$s'"); | |
845 | } | |
846 | } | |
e9ab8548 | 847 | $options['sort'] = implode(', ', $finalSort); |
1217e5e6 | 848 | } |
972322c5 | 849 | |
13c1cf91 | 850 | if ($options['sort'] && stristr($options['sort'], 'SELECT')) { |
ba93e7ad CW |
851 | throw new API_Exception('invalid string in sort options'); |
852 | } | |
13c1cf91 | 853 | |
6a488035 TO |
854 | if (!$queryObject) { |
855 | return $options; | |
856 | } | |
857 | //here comes the legacy support for $returnProperties, $inputParams e.g for contat_get | |
2b28667f | 858 | // if the query object is being used this should be used |
cf8f0fff CW |
859 | $inputParams = []; |
860 | $legacyreturnProperties = []; | |
861 | $otherVars = [ | |
35671d00 | 862 | 'sort', 'offset', 'rowCount', 'options', 'return', |
dba939ce | 863 | 'version', 'prettyprint', 'check_permissions', 'sequential', |
cf8f0fff | 864 | ]; |
6a488035 | 865 | foreach ($params as $n => $v) { |
a22a5119 | 866 | if (substr($n, 0, 7) === 'return.') { |
6a488035 TO |
867 | $legacyreturnProperties[substr($n, 7)] = $v; |
868 | } | |
a22a5119 | 869 | elseif ($n === 'id') { |
4846df91 | 870 | $inputParams[$lowercase_entity . '_id'] = $v; |
6a488035 | 871 | } |
35671d00 TO |
872 | elseif (in_array($n, $otherVars)) { |
873 | } | |
13c1cf91 | 874 | else { |
6a488035 | 875 | $inputParams[$n] = $v; |
13c1cf91 | 876 | if ($v && !is_array($v) && stristr($v, 'SELECT')) { |
ba93e7ad CW |
877 | throw new API_Exception('invalid string'); |
878 | } | |
6a488035 TO |
879 | } |
880 | } | |
881 | $options['return'] = array_merge($returnProperties, $legacyreturnProperties); | |
882 | $options['input_params'] = $inputParams; | |
883 | return $options; | |
884 | } | |
11e09c59 TO |
885 | |
886 | /** | |
9d32e6f7 | 887 | * Apply options (e.g. sort, limit, order by) to DAO object (prior to find). |
26728d3f | 888 | * |
cf470720 TO |
889 | * @param array $params |
890 | * Params array as passed into civicrm_api. | |
891 | * @param object $dao | |
892 | * DAO object. | |
26728d3f | 893 | * @param $entity |
a22a5119 | 894 | * |
895 | * @throws \API_Exception | |
896 | * @throws \CRM_Core_Exception | |
6a488035 TO |
897 | */ |
898 | function _civicrm_api3_apply_options_to_dao(&$params, &$dao, $entity) { | |
899 | ||
35671d00 | 900 | $options = _civicrm_api3_get_options_from_params($params, FALSE, $entity); |
22e263ad TO |
901 | if (!$options['is_count']) { |
902 | if (!empty($options['limit'])) { | |
35671d00 | 903 | $dao->limit((int) $options['offset'], (int) $options['limit']); |
ebddc2d9 | 904 | } |
972322c5 | 905 | if (!empty($options['sort'])) { |
1217e5e6 | 906 | $options['sort'] = CRM_Utils_Type::escape($options['sort'], 'MysqlOrderBy'); |
972322c5 | 907 | $dao->orderBy($options['sort']); |
908 | } | |
6a488035 TO |
909 | } |
910 | } | |
911 | ||
11e09c59 | 912 | /** |
9d32e6f7 EM |
913 | * Build fields array. |
914 | * | |
915 | * This is the array of fields as it relates to the given DAO | |
6a488035 | 916 | * returns unique fields as keys by default but if set but can return by DB fields |
971d41b1 CW |
917 | * |
918 | * @param CRM_Core_DAO $bao | |
645ee340 | 919 | * @param bool $unique |
971d41b1 CW |
920 | * |
921 | * @return array | |
6a488035 TO |
922 | */ |
923 | function _civicrm_api3_build_fields_array(&$bao, $unique = TRUE) { | |
924 | $fields = $bao->fields(); | |
925 | if ($unique) { | |
9b873358 | 926 | if (empty($fields['id'])) { |
4846df91 | 927 | $lowercase_entity = _civicrm_api_get_entity_name_from_camel(_civicrm_api_get_entity_name_from_dao($bao)); |
523c222f | 928 | if (isset($fields[$lowercase_entity . '_id'])) { |
929 | $fields['id'] = $fields[$lowercase_entity . '_id']; | |
930 | unset($fields[$lowercase_entity . '_id']); | |
931 | } | |
6a488035 TO |
932 | } |
933 | return $fields; | |
934 | } | |
935 | ||
936 | foreach ($fields as $field) { | |
937 | $dbFields[$field['name']] = $field; | |
938 | } | |
939 | return $dbFields; | |
940 | } | |
941 | ||
11e09c59 | 942 | /** |
9d32e6f7 EM |
943 | * Build fields array. |
944 | * | |
945 | * This is the array of fields as it relates to the given DAO | |
6a488035 | 946 | * returns unique fields as keys by default but if set but can return by DB fields |
971d41b1 | 947 | * |
488e7aba | 948 | * @param CRM_Core_DAO $bao |
fb7f68eb | 949 | * |
971d41b1 | 950 | * @return array |
6a488035 TO |
951 | */ |
952 | function _civicrm_api3_get_unique_name_array(&$bao) { | |
953 | $fields = $bao->fields(); | |
954 | foreach ($fields as $field => $values) { | |
35671d00 | 955 | $uniqueFields[$field] = CRM_Utils_Array::value('name', $values, $field); |
6a488035 TO |
956 | } |
957 | return $uniqueFields; | |
958 | } | |
959 | ||
6a488035 | 960 | /** |
9d32e6f7 | 961 | * Converts an DAO object to an array. |
6a488035 | 962 | * |
cf470720 TO |
963 | * @param CRM_Core_DAO $dao |
964 | * Object to convert. | |
c490a46a | 965 | * @param array $params |
26728d3f E |
966 | * @param bool $uniqueFields |
967 | * @param string $entity | |
941feb14 EM |
968 | * @param bool $autoFind |
969 | * | |
26728d3f | 970 | * @return array |
a22a5119 | 971 | * |
972 | * @throws \API_Exception | |
973 | * | |
974 | * @deprecated - DAO based retrieval is being phased out. | |
975 | * | |
6a488035 | 976 | */ |
ab5fa8f2 | 977 | function _civicrm_api3_dao_to_array($dao, $params = NULL, $uniqueFields = TRUE, $entity = "", $autoFind = TRUE) { |
cf8f0fff | 978 | $result = []; |
22e263ad | 979 | if (isset($params['options']) && !empty($params['options']['is_count'])) { |
972322c5 | 980 | return $dao->count(); |
981 | } | |
ab5fa8f2 | 982 | if (empty($dao)) { |
cf8f0fff | 983 | return []; |
ab5fa8f2 TO |
984 | } |
985 | if ($autoFind && !$dao->find()) { | |
cf8f0fff | 986 | return []; |
6a488035 TO |
987 | } |
988 | ||
22e263ad | 989 | if (isset($dao->count)) { |
972322c5 | 990 | return $dao->count; |
991 | } | |
6a488035 | 992 | |
0f3699bf | 993 | $fields = array_keys(_civicrm_api3_build_fields_array($dao, FALSE)); |
6a488035 | 994 | while ($dao->fetch()) { |
cf8f0fff | 995 | $tmp = []; |
6a488035 TO |
996 | foreach ($fields as $key) { |
997 | if (array_key_exists($key, $dao)) { | |
998 | // not sure on that one | |
999 | if ($dao->$key !== NULL) { | |
1000 | $tmp[$key] = $dao->$key; | |
1001 | } | |
1002 | } | |
1003 | } | |
1004 | $result[$dao->id] = $tmp; | |
8295042e | 1005 | |
22e263ad | 1006 | if (_civicrm_api3_custom_fields_are_required($entity, $params)) { |
e9ff5391 | 1007 | _civicrm_api3_custom_data_get($result[$dao->id], $params['check_permissions'], $entity, $dao->id); |
6a488035 TO |
1008 | } |
1009 | } | |
1010 | ||
6a488035 TO |
1011 | return $result; |
1012 | } | |
1013 | ||
8295042e | 1014 | /** |
61fe4988 EM |
1015 | * Determine if custom fields need to be retrieved. |
1016 | * | |
8295042e EM |
1017 | * We currently retrieve all custom fields or none at this level so if we know the entity |
1018 | * && 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 | |
8295042e | 1019 | * |
cf470720 TO |
1020 | * @param string $entity |
1021 | * Entity name in CamelCase. | |
971d41b1 | 1022 | * @param array $params |
8295042e EM |
1023 | * |
1024 | * @return bool | |
a22a5119 | 1025 | * @throws \API_Exception |
1026 | * | |
1027 | * @todo filter so only required fields are queried | |
8295042e EM |
1028 | */ |
1029 | function _civicrm_api3_custom_fields_are_required($entity, $params) { | |
1030 | if (!array_key_exists($entity, CRM_Core_BAO_CustomQuery::$extendsMap)) { | |
1031 | return FALSE; | |
1032 | } | |
1033 | $options = _civicrm_api3_get_options_from_params($params); | |
61fe4988 | 1034 | // We check for possibility of 'custom' => 1 as well as specific custom fields. |
8295042e | 1035 | $returnString = implode('', $options['return']) . implode('', array_keys($options['return'])); |
22e263ad | 1036 | if (stristr($returnString, 'custom')) { |
8295042e EM |
1037 | return TRUE; |
1038 | } | |
1039 | } | |
2b28667f | 1040 | |
6a488035 | 1041 | /** |
61fe4988 | 1042 | * Converts an object to an array. |
6a488035 | 1043 | * |
cf470720 TO |
1044 | * @param object $dao |
1045 | * (reference) object to convert. | |
1046 | * @param array $values | |
1047 | * (reference) array. | |
26728d3f | 1048 | * @param array|bool $uniqueFields |
6a488035 TO |
1049 | */ |
1050 | function _civicrm_api3_object_to_array(&$dao, &$values, $uniqueFields = FALSE) { | |
1051 | ||
1052 | $fields = _civicrm_api3_build_fields_array($dao, $uniqueFields); | |
1053 | foreach ($fields as $key => $value) { | |
1054 | if (array_key_exists($key, $dao)) { | |
1055 | $values[$key] = $dao->$key; | |
1056 | } | |
1057 | } | |
1058 | } | |
1059 | ||
11e09c59 | 1060 | /** |
9d32e6f7 EM |
1061 | * Wrapper for _civicrm_object_to_array when api supports unique fields. |
1062 | * | |
645ee340 EM |
1063 | * @param $dao |
1064 | * @param $values | |
9d32e6f7 | 1065 | * |
645ee340 | 1066 | * @return array |
6a488035 TO |
1067 | */ |
1068 | function _civicrm_api3_object_to_array_unique_fields(&$dao, &$values) { | |
1069 | return _civicrm_api3_object_to_array($dao, $values, TRUE); | |
1070 | } | |
1071 | ||
1072 | /** | |
9d32e6f7 | 1073 | * Format custom parameters. |
6a488035 TO |
1074 | * |
1075 | * @param array $params | |
1076 | * @param array $values | |
cf470720 TO |
1077 | * @param string $extends |
1078 | * Entity that this custom field extends (e.g. contribution, event, contact). | |
1079 | * @param string $entityId | |
1080 | * ID of entity per $extends. | |
6a488035 TO |
1081 | */ |
1082 | function _civicrm_api3_custom_format_params($params, &$values, $extends, $entityId = NULL) { | |
cf8f0fff | 1083 | $values['custom'] = []; |
e9f2f3b1 EM |
1084 | $checkCheckBoxField = FALSE; |
1085 | $entity = $extends; | |
cf8f0fff | 1086 | if (in_array($extends, ['Household', 'Individual', 'Organization'])) { |
e9f2f3b1 EM |
1087 | $entity = 'Contact'; |
1088 | } | |
1089 | ||
cf8f0fff | 1090 | $fields = civicrm_api($entity, 'getfields', ['version' => 3, 'action' => 'create']); |
22e263ad | 1091 | if (!$fields['is_error']) { |
e9f2f3b1 EM |
1092 | // not sure if fields could be error - maybe change to using civicrm_api3 wrapper later - this is conservative |
1093 | $fields = $fields['values']; | |
1094 | $checkCheckBoxField = TRUE; | |
1095 | } | |
1096 | ||
6a488035 TO |
1097 | foreach ($params as $key => $value) { |
1098 | list($customFieldID, $customValueID) = CRM_Core_BAO_CustomField::getKeyID($key, TRUE); | |
35671d00 | 1099 | if ($customFieldID && (!is_null($value))) { |
24e4bf08 | 1100 | if ($checkCheckBoxField && !empty($fields['custom_' . $customFieldID]) && $fields['custom_' . $customFieldID]['html_type'] == 'CheckBox') { |
e9f2f3b1 EM |
1101 | formatCheckBoxField($value, 'custom_' . $customFieldID, $entity); |
1102 | } | |
4c16123d | 1103 | |
6a488035 | 1104 | CRM_Core_BAO_CustomField::formatCustomField($customFieldID, $values['custom'], |
211353a8 | 1105 | $value, $extends, $customValueID, $entityId, FALSE, FALSE, TRUE |
6a488035 TO |
1106 | ); |
1107 | } | |
1108 | } | |
1109 | } | |
1110 | ||
8295042e | 1111 | /** |
9d32e6f7 EM |
1112 | * Format parameters for create action. |
1113 | * | |
c490a46a | 1114 | * @param array $params |
8295042e EM |
1115 | * @param $entity |
1116 | */ | |
1117 | function _civicrm_api3_format_params_for_create(&$params, $entity) { | |
cf8f0fff | 1118 | $nonGenericEntities = ['Contact', 'Individual', 'Household', 'Organization']; |
8295042e | 1119 | |
3fb8828b | 1120 | $customFieldEntities = array_diff_key(CRM_Core_SelectValues::customGroupExtends(), array_fill_keys($nonGenericEntities, 1)); |
22e263ad | 1121 | if (!array_key_exists($entity, $customFieldEntities)) { |
8295042e EM |
1122 | return; |
1123 | } | |
cf8f0fff | 1124 | $values = []; |
8295042e EM |
1125 | _civicrm_api3_custom_format_params($params, $values, $entity); |
1126 | $params = array_merge($params, $values); | |
1127 | } | |
1128 | ||
e9f2f3b1 | 1129 | /** |
9d32e6f7 EM |
1130 | * We can't rely on downstream to add separators to checkboxes so we'll check here. |
1131 | * | |
1132 | * We should look at pushing to BAO function | |
e9f2f3b1 EM |
1133 | * and / or validate function but this is a safe place for now as it has massive test coverage & we can keep the change very specific |
1134 | * note that this is specifically tested in the GRANT api test case so later refactoring should use that as a checking point | |
1135 | * | |
1136 | * We will only alter the value if we are sure that changing it will make it correct - if it appears wrong but does not appear to have a clear fix we | |
1137 | * don't touch - lots of very cautious code in here | |
1138 | * | |
4ee91976 EM |
1139 | * The resulting array should look like |
1140 | * array( | |
1141 | * 'key' => 1, | |
1142 | * 'key1' => 1, | |
1143 | * ); | |
1144 | * | |
1145 | * OR one or more keys wrapped in a CRM_Core_DAO::VALUE_SEPARATOR - either it accepted by the receiving function | |
1146 | * | |
e9f2f3b1 EM |
1147 | * @todo - we are probably skipping handling disabled options as presumably getoptions is not giving us them. This should be non-regressive but might |
1148 | * be fixed in future | |
1149 | * | |
9d32e6f7 EM |
1150 | * @param mixed $checkboxFieldValue |
1151 | * @param string $customFieldLabel | |
1152 | * @param string $entity | |
e9f2f3b1 EM |
1153 | */ |
1154 | function formatCheckBoxField(&$checkboxFieldValue, $customFieldLabel, $entity) { | |
1155 | ||
1156 | if (is_string($checkboxFieldValue) && stristr($checkboxFieldValue, CRM_Core_DAO::VALUE_SEPARATOR)) { | |
9d32e6f7 | 1157 | // We can assume it's pre-formatted. |
e9f2f3b1 EM |
1158 | return; |
1159 | } | |
cf8f0fff | 1160 | $options = civicrm_api($entity, 'getoptions', ['field' => $customFieldLabel, 'version' => 3]); |
e9f2f3b1 | 1161 | if (!empty($options['is_error'])) { |
9d32e6f7 | 1162 | // The check is precautionary - can probably be removed later. |
e9f2f3b1 EM |
1163 | return; |
1164 | } | |
1165 | ||
1166 | $options = $options['values']; | |
1167 | $validValue = TRUE; | |
1168 | if (is_array($checkboxFieldValue)) { | |
1169 | foreach ($checkboxFieldValue as $key => $value) { | |
1170 | if (!array_key_exists($key, $options)) { | |
1171 | $validValue = FALSE; | |
1172 | } | |
1173 | } | |
1174 | if ($validValue) { | |
1175 | // we have been passed an array that is already in the 'odd' custom field format | |
1176 | return; | |
1177 | } | |
1178 | } | |
1179 | ||
1180 | // so we either have an array that is not keyed by the value or we have a string that doesn't hold separators | |
1181 | // if the array only has one item we'll treat it like any other string | |
1182 | if (is_array($checkboxFieldValue) && count($checkboxFieldValue) == 1) { | |
1183 | $possibleValue = reset($checkboxFieldValue); | |
1184 | } | |
1185 | if (is_string($checkboxFieldValue)) { | |
1186 | $possibleValue = $checkboxFieldValue; | |
1187 | } | |
1188 | if (isset($possibleValue) && array_key_exists($possibleValue, $options)) { | |
1189 | $checkboxFieldValue = CRM_Core_DAO::VALUE_SEPARATOR . $possibleValue . CRM_Core_DAO::VALUE_SEPARATOR; | |
1190 | return; | |
1191 | } | |
1192 | elseif (is_array($checkboxFieldValue)) { | |
1193 | // so this time around we are considering the values in the array | |
1194 | $possibleValues = $checkboxFieldValue; | |
1195 | $formatValue = TRUE; | |
1196 | } | |
1197 | elseif (stristr($checkboxFieldValue, ',')) { | |
1198 | $formatValue = TRUE; | |
e834996a EM |
1199 | //lets see if we should separate it - we do this near the end so we |
1200 | // ensure we have already checked that the comma is not part of a legitimate match | |
1201 | // and of course, we don't make any changes if we don't now have matches | |
e9f2f3b1 EM |
1202 | $possibleValues = explode(',', $checkboxFieldValue); |
1203 | } | |
1204 | else { | |
1205 | // run out of ideas as to what the format might be - if it's a string it doesn't match with or without the ',' | |
1206 | return; | |
1207 | } | |
1208 | ||
1209 | foreach ($possibleValues as $index => $possibleValue) { | |
1210 | if (array_key_exists($possibleValue, $options)) { | |
1211 | // do nothing - we will leave formatValue set to true unless another value is not found (which would cause us to ignore the whole value set) | |
1212 | } | |
1213 | elseif (array_key_exists(trim($possibleValue), $options)) { | |
1214 | $possibleValues[$index] = trim($possibleValue); | |
1215 | } | |
1216 | else { | |
1217 | $formatValue = FALSE; | |
1218 | } | |
1219 | } | |
1220 | if ($formatValue) { | |
1221 | $checkboxFieldValue = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR, $possibleValues) . CRM_Core_DAO::VALUE_SEPARATOR; | |
1222 | } | |
1223 | } | |
1224 | ||
11e09c59 | 1225 | /** |
9d32e6f7 | 1226 | * Function to do a 'standard' api get - when the api is only doing a $bao->find then use this. |
6a488035 | 1227 | * |
cf470720 TO |
1228 | * @param string $bao_name |
1229 | * Name of BAO. | |
1230 | * @param array $params | |
1231 | * Params from api. | |
1232 | * @param bool $returnAsSuccess | |
1233 | * Return in api success format. | |
26728d3f | 1234 | * @param string $entity |
01c8287d TO |
1235 | * @param CRM_Utils_SQL_Select|NULL $sql |
1236 | * Extra SQL bits to add to the query. For filtering current events, this might be: | |
1237 | * CRM_Utils_SQL_Select::fragment()->where('(start_date >= CURDATE() || end_date >= CURDATE())'); | |
0f3699bf | 1238 | * @param bool $uniqueFields |
1239 | * Should unique field names be returned (for backward compatibility) | |
26728d3f E |
1240 | * |
1241 | * @return array | |
6a488035 | 1242 | */ |
357f9d0e | 1243 | function _civicrm_api3_basic_get($bao_name, $params, $returnAsSuccess = TRUE, $entity = "", $sql = NULL, $uniqueFields = FALSE) { |
7560c9af | 1244 | $entity = $entity ?: CRM_Core_DAO_AllCoreTables::getBriefName(str_replace('_BAO_', '_DAO_', $bao_name)); |
8bcc0d86 CW |
1245 | $options = _civicrm_api3_get_options_from_params($params); |
1246 | ||
8e8bf584 | 1247 | $query = new \Civi\API\Api3SelectQuery($entity, CRM_Utils_Array::value('check_permissions', $params, FALSE)); |
8bcc0d86 CW |
1248 | $query->where = $params; |
1249 | if ($options['is_count']) { | |
cf8f0fff | 1250 | $query->select = ['count_rows']; |
8bcc0d86 CW |
1251 | } |
1252 | else { | |
1253 | $query->select = array_keys(array_filter($options['return'])); | |
1254 | $query->orderBy = $options['sort']; | |
1255 | $query->isFillUniqueFields = $uniqueFields; | |
1256 | } | |
1257 | $query->limit = $options['limit']; | |
1258 | $query->offset = $options['offset']; | |
e47bcddb CW |
1259 | $query->merge($sql); |
1260 | $result = $query->run(); | |
8bcc0d86 | 1261 | |
6a488035 | 1262 | if ($returnAsSuccess) { |
357f9d0e | 1263 | return civicrm_api3_create_success($result, $params, $entity, 'get'); |
6a488035 | 1264 | } |
357f9d0e | 1265 | return $result; |
6a488035 TO |
1266 | } |
1267 | ||
11e09c59 | 1268 | /** |
9d32e6f7 | 1269 | * Function to do a 'standard' api create - when the api is only doing a $bao::create then use this. |
1cfa04c4 | 1270 | * |
cf470720 TO |
1271 | * @param string $bao_name |
1272 | * Name of BAO Class. | |
1273 | * @param array $params | |
1274 | * Parameters passed into the api call. | |
1275 | * @param string $entity | |
1276 | * Entity - pass in if entity is non-standard & required $ids array. | |
1cfa04c4 EM |
1277 | * |
1278 | * @throws API_Exception | |
db83e3a3 | 1279 | * @throws \Civi\API\Exception\UnauthorizedException |
26728d3f | 1280 | * @return array |
6a488035 | 1281 | */ |
53ed8466 | 1282 | function _civicrm_api3_basic_create($bao_name, &$params, $entity = NULL) { |
db83e3a3 | 1283 | _civicrm_api3_check_edit_permissions($bao_name, $params); |
8295042e | 1284 | _civicrm_api3_format_params_for_create($params, $entity); |
6a488035 | 1285 | $args = array(&$params); |
244bbdd8 | 1286 | if ($entity) { |
cf8f0fff | 1287 | $ids = [$entity => CRM_Utils_Array::value('id', $params)]; |
6a488035 TO |
1288 | $args[] = &$ids; |
1289 | } | |
acde3ae0 | 1290 | |
6a488035 TO |
1291 | if (method_exists($bao_name, 'create')) { |
1292 | $fct = 'create'; | |
acde3ae0 | 1293 | $fct_name = $bao_name . '::' . $fct; |
cf8f0fff | 1294 | $bao = call_user_func_array([$bao_name, $fct], $args); |
6a488035 TO |
1295 | } |
1296 | elseif (method_exists($bao_name, 'add')) { | |
1297 | $fct = 'add'; | |
acde3ae0 | 1298 | $fct_name = $bao_name . '::' . $fct; |
cf8f0fff | 1299 | $bao = call_user_func_array([$bao_name, $fct], $args); |
6a488035 | 1300 | } |
acde3ae0 TO |
1301 | else { |
1302 | $fct_name = '_civicrm_api3_basic_create_fallback'; | |
1303 | $bao = _civicrm_api3_basic_create_fallback($bao_name, $params); | |
6a488035 | 1304 | } |
acde3ae0 | 1305 | |
6a488035 | 1306 | if (is_null($bao)) { |
acde3ae0 | 1307 | return civicrm_api3_create_error('Entity not created (' . $fct_name . ')'); |
6a488035 | 1308 | } |
736eec43 | 1309 | elseif (is_a($bao, 'CRM_Core_Error')) { |
e4f46be0 | 1310 | //some weird circular thing means the error takes itself as an argument |
736eec43 E |
1311 | $msg = $bao->getMessages($bao); |
1312 | // the api deals with entities on a one-by-one basis. However, the contribution bao pushes entities | |
1313 | // onto the error object - presumably because the contribution import is not handling multiple errors correctly | |
1314 | // so we need to reset the error object here to avoid getting concatenated errors | |
1315 | //@todo - the mulitple error handling should be moved out of the contribution object to the import / multiple entity processes | |
1316 | CRM_Core_Error::singleton()->reset(); | |
1317 | throw new API_Exception($msg); | |
1318 | } | |
6a488035 | 1319 | else { |
3fb8828b | 1320 | // If we have custom fields the BAO may have taken care of it or we may have to. |
1321 | // $extendsMap provides a pretty good hard-coded list of BAOs that take care of the custom data. | |
1322 | if (isset($params['custom']) && empty(CRM_Core_BAO_CustomQuery::$extendsMap[$entity])) { | |
1323 | CRM_Core_BAO_CustomValueTable::store($params['custom'], CRM_Core_DAO_AllCoreTables::getTableForClass(CRM_Core_DAO_AllCoreTables::getFullName($entity)), $bao->id); | |
1324 | } | |
cf8f0fff | 1325 | $values = []; |
6a488035 | 1326 | _civicrm_api3_object_to_array($bao, $values[$bao->id]); |
504a78f6 | 1327 | return civicrm_api3_create_success($values, $params, $entity, 'create', $bao); |
6a488035 TO |
1328 | } |
1329 | } | |
1330 | ||
acde3ae0 TO |
1331 | /** |
1332 | * For BAO's which don't have a create() or add() functions, use this fallback implementation. | |
1333 | * | |
26728d3f | 1334 | * @fixme There's an intuitive sense that this behavior should be defined somehow in the BAO/DAO class |
acde3ae0 TO |
1335 | * structure. In practice, that requires a fair amount of refactoring and/or kludgery. |
1336 | * | |
1337 | * @param string $bao_name | |
1338 | * @param array $params | |
916b48b6 VU |
1339 | * |
1340 | * @throws API_Exception | |
9d32e6f7 EM |
1341 | * |
1342 | * @return CRM_Core_DAO|NULL | |
1343 | * An instance of the BAO | |
acde3ae0 TO |
1344 | */ |
1345 | function _civicrm_api3_basic_create_fallback($bao_name, &$params) { | |
a9739e5d CW |
1346 | $dao_name = get_parent_class($bao_name); |
1347 | if ($dao_name === 'CRM_Core_DAO' || !$dao_name) { | |
1348 | $dao_name = $bao_name; | |
1349 | } | |
1350 | $entityName = CRM_Core_DAO_AllCoreTables::getBriefName($dao_name); | |
acde3ae0 | 1351 | if (empty($entityName)) { |
cf8f0fff | 1352 | throw new API_Exception("Class \"$bao_name\" does not map to an entity name", "unmapped_class_to_entity", [ |
acde3ae0 | 1353 | 'class_name' => $bao_name, |
cf8f0fff | 1354 | ]); |
acde3ae0 TO |
1355 | } |
1356 | $hook = empty($params['id']) ? 'create' : 'edit'; | |
1357 | ||
1358 | CRM_Utils_Hook::pre($hook, $entityName, CRM_Utils_Array::value('id', $params), $params); | |
a9739e5d | 1359 | $instance = new $dao_name(); |
fc944198 | 1360 | $instance->copyValues($params); |
acde3ae0 TO |
1361 | $instance->save(); |
1362 | CRM_Utils_Hook::post($hook, $entityName, $instance->id, $instance); | |
1363 | ||
1364 | return $instance; | |
1365 | } | |
1366 | ||
11e09c59 | 1367 | /** |
9d32e6f7 EM |
1368 | * Function to do a 'standard' api del. |
1369 | * | |
1370 | * When the api is only doing a $bao::del then use this if api::del doesn't exist it will try DAO delete method. | |
3d0d359e | 1371 | * |
100fef9d | 1372 | * @param string $bao_name |
c490a46a | 1373 | * @param array $params |
3d0d359e | 1374 | * |
a6c01b45 | 1375 | * @return array |
72b3a70c | 1376 | * API result array |
a22a5119 | 1377 | * |
3d0d359e | 1378 | * @throws API_Exception |
db83e3a3 | 1379 | * @throws \Civi\API\Exception\UnauthorizedException |
a22a5119 | 1380 | * @throws \CiviCRM_API3_Exception |
6a488035 TO |
1381 | */ |
1382 | function _civicrm_api3_basic_delete($bao_name, &$params) { | |
cf8f0fff CW |
1383 | civicrm_api3_verify_mandatory($params, NULL, ['id']); |
1384 | _civicrm_api3_check_edit_permissions($bao_name, ['id' => $params['id']]); | |
a22a5119 | 1385 | $args = [&$params['id']]; |
6a488035 | 1386 | if (method_exists($bao_name, 'del')) { |
a60c0bc8 SL |
1387 | $dao = new $bao_name(); |
1388 | $dao->id = $params['id']; | |
1389 | if ($dao->find()) { | |
cf8f0fff | 1390 | $bao = call_user_func_array([$bao_name, 'del'], $args); |
a60c0bc8 SL |
1391 | if ($bao !== FALSE) { |
1392 | return civicrm_api3_create_success(); | |
1393 | } | |
1394 | throw new API_Exception('Could not delete entity id ' . $params['id']); | |
a65e2e55 | 1395 | } |
fb32de45 | 1396 | throw new API_Exception('Could not delete entity id ' . $params['id']); |
6a488035 TO |
1397 | } |
1398 | elseif (method_exists($bao_name, 'delete')) { | |
1399 | $dao = new $bao_name(); | |
1400 | $dao->id = $params['id']; | |
1401 | if ($dao->find()) { | |
1402 | while ($dao->fetch()) { | |
1403 | $dao->delete(); | |
1404 | return civicrm_api3_create_success(); | |
1405 | } | |
1406 | } | |
1407 | else { | |
fb32de45 | 1408 | throw new API_Exception('Could not delete entity id ' . $params['id']); |
6a488035 TO |
1409 | } |
1410 | } | |
1411 | ||
fb32de45 | 1412 | throw new API_Exception('no delete method found'); |
6a488035 TO |
1413 | } |
1414 | ||
11e09c59 | 1415 | /** |
9d32e6f7 EM |
1416 | * Get custom data for the given entity & Add it to the returnArray. |
1417 | * | |
1418 | * This looks like 'custom_123' = 'custom string' AND | |
1419 | * 'custom_123_1' = 'custom string' | |
6a488035 TO |
1420 | * Where 123 is field value & 1 is the id within the custom group data table (value ID) |
1421 | * | |
cf470720 TO |
1422 | * @param array $returnArray |
1423 | * Array to append custom data too - generally $result[4] where 4 is the entity id. | |
8089541a | 1424 | * @param $checkPermission |
cf470720 TO |
1425 | * @param string $entity |
1426 | * E.g membership, event. | |
100fef9d | 1427 | * @param int $entity_id |
cf470720 TO |
1428 | * @param int $groupID |
1429 | * Per CRM_Core_BAO_CustomGroup::getTree. | |
1430 | * @param int $subType | |
1431 | * E.g. membership_type_id where custom data doesn't apply to all membership types. | |
1432 | * @param string $subName | |
1433 | * Subtype of entity. | |
a22a5119 | 1434 | * |
1435 | * @throws \CRM_Core_Exception | |
6a488035 | 1436 | */ |
e9ff5391 | 1437 | function _civicrm_api3_custom_data_get(&$returnArray, $checkPermission, $entity, $entity_id, $groupID = NULL, $subType = NULL, $subName = NULL) { |
9af2925b | 1438 | $groupTree = CRM_Core_BAO_CustomGroup::getTree($entity, |
79363422 | 1439 | NULL, |
6a488035 TO |
1440 | $entity_id, |
1441 | $groupID, | |
b62bc939 EM |
1442 | NULL, |
1443 | $subName, | |
1444 | TRUE, | |
1445 | NULL, | |
e9ff5391 | 1446 | TRUE, |
1447 | $checkPermission | |
6a488035 | 1448 | ); |
1273d77c | 1449 | $groupTree = CRM_Core_BAO_CustomGroup::formatGroupTree($groupTree, 1); |
cf8f0fff | 1450 | $customValues = []; |
6a488035 | 1451 | CRM_Core_BAO_CustomGroup::setDefaults($groupTree, $customValues); |
cf8f0fff | 1452 | $fieldInfo = []; |
e0995951 CW |
1453 | foreach ($groupTree as $set) { |
1454 | $fieldInfo += $set['fields']; | |
1455 | } | |
6a488035 TO |
1456 | if (!empty($customValues)) { |
1457 | foreach ($customValues as $key => $val) { | |
e0995951 CW |
1458 | // per standard - return custom_fieldID |
1459 | $id = CRM_Core_BAO_CustomField::getKeyID($key); | |
1460 | $returnArray['custom_' . $id] = $val; | |
1461 | ||
1462 | //not standard - but some api did this so guess we should keep - cheap as chips | |
1463 | $returnArray[$key] = $val; | |
6a488035 | 1464 | |
e0995951 | 1465 | // Shim to restore legacy behavior of ContactReference custom fields |
a22a5119 | 1466 | if (!empty($fieldInfo[$id]) && $fieldInfo[$id]['data_type'] === 'ContactReference') { |
e0995951 CW |
1467 | $returnArray['custom_' . $id . '_id'] = $returnArray[$key . '_id'] = $val; |
1468 | $returnArray['custom_' . $id] = $returnArray[$key] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $val, 'sort_name'); | |
6a488035 TO |
1469 | } |
1470 | } | |
1471 | } | |
1472 | } | |
1473 | ||
b7c239b6 SB |
1474 | /** |
1475 | * Used by the Validate API. | |
a22a5119 | 1476 | * |
b7c239b6 SB |
1477 | * @param string $entity |
1478 | * @param string $action | |
1479 | * @param array $params | |
1480 | * | |
1481 | * @return array $errors | |
a22a5119 | 1482 | * @throws \CiviCRM_API3_Exception |
b7c239b6 SB |
1483 | */ |
1484 | function _civicrm_api3_validate($entity, $action, $params) { | |
cf8f0fff CW |
1485 | $errors = []; |
1486 | $fields = civicrm_api3($entity, 'getfields', ['sequential' => 1, 'api_action' => $action]); | |
969ca694 | 1487 | $fields = $fields['values']; |
b7c239b6 | 1488 | |
969ca694 | 1489 | // Check for required fields. |
6e4339c4 SB |
1490 | foreach ($fields as $values) { |
1491 | if (!empty($values['api.required']) && empty($params[$values['name']])) { | |
cf8f0fff | 1492 | $errors[$values['name']] = [ |
a22a5119 | 1493 | 'message' => 'Mandatory key(s) missing from params array: ' . $values['name'], |
1494 | 'code' => 'mandatory_missing', | |
cf8f0fff | 1495 | ]; |
969ca694 SB |
1496 | } |
1497 | } | |
b7c239b6 SB |
1498 | |
1499 | // Select only the fields which have been input as a param. | |
cf8f0fff | 1500 | $finalfields = []; |
6e4339c4 SB |
1501 | foreach ($fields as $values) { |
1502 | if (array_key_exists($values['name'], $params)) { | |
1503 | $finalfields[] = $values; | |
1504 | } | |
1505 | } | |
b7c239b6 SB |
1506 | |
1507 | // This derives heavily from the function "_civicrm_api3_validate_fields". | |
1508 | // However, the difference is that try-catch blocks are nested in the loop, making it | |
1509 | // possible for us to get all errors in one go. | |
6e4339c4 SB |
1510 | foreach ($finalfields as $fieldInfo) { |
1511 | $fieldName = $fieldInfo['name']; | |
969ca694 | 1512 | try { |
6e4339c4 | 1513 | _civicrm_api3_validate_switch_cases($fieldName, $fieldInfo, $entity, $params); |
969ca694 SB |
1514 | } |
1515 | catch (Exception $e) { | |
cf8f0fff | 1516 | $errors[$fieldName] = [ |
6e4339c4 SB |
1517 | 'message' => $e->getMessage(), |
1518 | 'code' => 'incorrect_value', | |
cf8f0fff | 1519 | ]; |
969ca694 SB |
1520 | } |
1521 | } | |
b7c239b6 | 1522 | |
cf8f0fff | 1523 | return [$errors]; |
969ca694 | 1524 | } |
8089541a | 1525 | |
969ca694 SB |
1526 | /** |
1527 | * Used by the Validate API. | |
8089541a | 1528 | * @param $fieldName |
969ca694 SB |
1529 | * @param array $fieldInfo |
1530 | * @param string $entity | |
1531 | * @param array $params | |
1532 | * | |
8089541a | 1533 | * @throws API_Exception |
969ca694 SB |
1534 | * @throws Exception |
1535 | */ | |
6e4339c4 | 1536 | function _civicrm_api3_validate_switch_cases($fieldName, $fieldInfo, $entity, $params) { |
969ca694 SB |
1537 | switch (CRM_Utils_Array::value('type', $fieldInfo)) { |
1538 | case CRM_Utils_Type::T_INT: | |
1539 | _civicrm_api3_validate_integer($params, $fieldName, $fieldInfo, $entity); | |
1540 | break; | |
1541 | ||
1542 | case CRM_Utils_Type::T_DATE: | |
1543 | case CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME: | |
1544 | case CRM_Utils_Type::T_TIMESTAMP: | |
1545 | //field is of type date or datetime | |
1546 | _civicrm_api3_validate_date($params, $fieldName, $fieldInfo); | |
1547 | break; | |
1548 | ||
1549 | case CRM_Utils_Type::T_TEXT: | |
969ca694 SB |
1550 | case CRM_Utils_Type::T_STRING: |
1551 | _civicrm_api3_validate_string($params, $fieldName, $fieldInfo, $entity); | |
1552 | break; | |
1553 | ||
1554 | case CRM_Utils_Type::T_MONEY: | |
1555 | list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName); | |
6e4339c4 | 1556 | |
969ca694 SB |
1557 | foreach ((array) $fieldValue as $fieldvalue) { |
1558 | if (!CRM_Utils_Rule::money($fieldvalue) && !empty($fieldvalue)) { | |
a22a5119 | 1559 | throw new Exception($fieldName . ' is not a valid amount: ' . $params[$fieldName]); |
b7c239b6 | 1560 | } |
969ca694 SB |
1561 | } |
1562 | break; | |
b7c239b6 | 1563 | } |
b7c239b6 SB |
1564 | } |
1565 | ||
11e09c59 | 1566 | /** |
9d32e6f7 EM |
1567 | * Validate fields being passed into API. |
1568 | * | |
1569 | * This function relies on the getFields function working accurately | |
4f94e3fa | 1570 | * for the given API. |
6a488035 TO |
1571 | * |
1572 | * As of writing only date was implemented. | |
9d32e6f7 | 1573 | * |
6a488035 TO |
1574 | * @param string $entity |
1575 | * @param string $action | |
cf470720 TO |
1576 | * @param array $params |
1577 | * -. | |
1578 | * @param array $fields | |
1579 | * Response from getfields all variables are the same as per civicrm_api. | |
9d32e6f7 | 1580 | * |
916b48b6 | 1581 | * @throws Exception |
6a488035 | 1582 | */ |
3b45eb1c | 1583 | function _civicrm_api3_validate_fields($entity, $action, &$params, $fields) { |
2930d67a | 1584 | //CRM-15792 handle datetime for custom fields below code handles chain api call |
1585 | $chainApikeys = array_flip(preg_grep("/^api./", array_keys($params))); | |
1586 | if (!empty($chainApikeys) && is_array($chainApikeys)) { | |
1587 | foreach ($chainApikeys as $key => $value) { | |
1588 | if (is_array($params[$key])) { | |
1589 | $chainApiParams = array_intersect_key($fields, $params[$key]); | |
1590 | $customFields = array_fill_keys(array_keys($params[$key]), $key); | |
1591 | } | |
1592 | } | |
1593 | } | |
94359f7e | 1594 | $fields = array_intersect_key($fields, $params); |
2930d67a | 1595 | if (!empty($chainApiParams)) { |
1596 | $fields = array_merge($fields, $chainApiParams); | |
1597 | } | |
70f7ba9e | 1598 | foreach ($fields as $fieldName => $fieldInfo) { |
6a488035 TO |
1599 | switch (CRM_Utils_Array::value('type', $fieldInfo)) { |
1600 | case CRM_Utils_Type::T_INT: | |
1601 | //field is of type integer | |
70f7ba9e | 1602 | _civicrm_api3_validate_integer($params, $fieldName, $fieldInfo, $entity); |
6a488035 TO |
1603 | break; |
1604 | ||
2930d67a | 1605 | case CRM_Utils_Type::T_DATE: |
1606 | case CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME: | |
9bee5ea2 | 1607 | case CRM_Utils_Type::T_TIMESTAMP: |
6a488035 | 1608 | //field is of type date or datetime |
2930d67a | 1609 | if (!empty($customFields) && array_key_exists($fieldName, $customFields)) { |
1610 | $dateParams = &$params[$customFields[$fieldName]]; | |
1611 | } | |
1612 | else { | |
1613 | $dateParams = &$params; | |
1614 | } | |
1615 | _civicrm_api3_validate_date($dateParams, $fieldName, $fieldInfo); | |
6a488035 | 1616 | break; |
83abdecd | 1617 | |
978c5e8f | 1618 | case CRM_Utils_Type::T_TEXT: |
83abdecd | 1619 | case CRM_Utils_Type::T_STRING: |
70f7ba9e | 1620 | _civicrm_api3_validate_string($params, $fieldName, $fieldInfo, $entity); |
6a488035 TO |
1621 | break; |
1622 | ||
1623 | case CRM_Utils_Type::T_MONEY: | |
afa0b07c | 1624 | list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName); |
1625 | if (strpos($op, 'NULL') !== FALSE || strpos($op, 'EMPTY') !== FALSE) { | |
1626 | break; | |
1627 | } | |
971d41b1 | 1628 | foreach ((array) $fieldValue as $fieldvalue) { |
7d543448 | 1629 | if (!CRM_Utils_Rule::money($fieldvalue) && !empty($fieldvalue)) { |
3a6eb174 | 1630 | throw new Exception($fieldName . " is not a valid amount: " . $params[$fieldName]); |
1631 | } | |
6a488035 | 1632 | } |
3a6eb174 | 1633 | break; |
6a488035 | 1634 | } |
4f94e3fa MM |
1635 | } |
1636 | } | |
6a488035 | 1637 | |
4f94e3fa MM |
1638 | /** |
1639 | * Validate foreign key values of fields being passed into API. | |
1640 | * | |
1641 | * This function relies on the getFields function working accurately | |
1642 | * for the given API. | |
1643 | * | |
1644 | * @param string $entity | |
1645 | * @param string $action | |
1646 | * @param array $params | |
1647 | * | |
1648 | * @param array $fields | |
1649 | * Response from getfields all variables are the same as per civicrm_api. | |
1650 | * | |
1651 | * @throws Exception | |
1652 | */ | |
1653 | function _civicrm_api3_validate_foreign_keys($entity, $action, &$params, $fields) { | |
1654 | // intensive checks - usually only called after DB level fail | |
1655 | foreach ($fields as $fieldName => $fieldInfo) { | |
1656 | if (!empty($fieldInfo['FKClassName'])) { | |
1657 | if (!empty($params[$fieldName])) { | |
2e537447 | 1658 | foreach ((array) $params[$fieldName] as $fieldValue) { |
7f1a780c | 1659 | _civicrm_api3_validate_constraint($fieldValue, $fieldName, $fieldInfo, $entity); |
2e537447 | 1660 | } |
6a488035 | 1661 | } |
4f94e3fa | 1662 | elseif (!empty($fieldInfo['required'])) { |
43fc3f38 | 1663 | throw new Exception("DB Constraint Violation - $fieldName should possibly be marked as mandatory for $entity,$action API. If so, please raise a bug report."); |
6a488035 TO |
1664 | } |
1665 | } | |
4f94e3fa MM |
1666 | if (!empty($fieldInfo['api.unique'])) { |
1667 | $params['entity'] = $entity; | |
1668 | _civicrm_api3_validate_unique_key($params, $fieldName); | |
1669 | } | |
6a488035 TO |
1670 | } |
1671 | } | |
1672 | ||
11e09c59 | 1673 | /** |
6a488035 | 1674 | * Validate date fields being passed into API. |
9d32e6f7 | 1675 | * |
6a488035 TO |
1676 | * It currently converts both unique fields and DB field names to a mysql date. |
1677 | * @todo - probably the unique field handling & the if exists handling is now done before this | |
1678 | * function is reached in the wrapper - can reduce this code down to assume we | |
1679 | * are only checking the passed in field | |
1680 | * | |
1681 | * It also checks against the RULE:date function. This is a centralisation of code that was scattered and | |
1682 | * may not be the best thing to do. There is no code level documentation on the existing functions to work off | |
1683 | * | |
cf470720 TO |
1684 | * @param array $params |
1685 | * Params from civicrm_api. | |
1686 | * @param string $fieldName | |
1687 | * Uniquename of field being checked. | |
1688 | * @param array $fieldInfo | |
1689 | * Array of fields from getfields function. | |
9d32e6f7 | 1690 | * |
916b48b6 | 1691 | * @throws Exception |
6a488035 | 1692 | */ |
70f7ba9e | 1693 | function _civicrm_api3_validate_date(&$params, &$fieldName, &$fieldInfo) { |
afa0b07c | 1694 | list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName); |
1695 | if (strpos($op, 'NULL') !== FALSE || strpos($op, 'EMPTY') !== FALSE) { | |
1696 | return; | |
1697 | } | |
325033b9 | 1698 | |
1699 | if ($fieldValue === 'null' && empty($fieldInfo['api.required'])) { | |
1700 | // This is the wierd & wonderful way PEAR sets null. | |
1701 | return; | |
1702 | } | |
1703 | ||
6a488035 | 1704 | //should we check first to prevent it from being copied if they have passed in sql friendly format? |
a7488080 | 1705 | if (!empty($params[$fieldInfo['name']])) { |
3c151c70 | 1706 | $fieldValue = _civicrm_api3_getValidDate($fieldValue, $fieldInfo['name'], $fieldInfo['type']); |
6a488035 | 1707 | } |
3c151c70 | 1708 | if ((CRM_Utils_Array::value('name', $fieldInfo) != $fieldName) && !empty($fieldValue)) { |
1709 | $fieldValue = _civicrm_api3_getValidDate($fieldValue, $fieldName, $fieldInfo['type']); | |
9bee5ea2 | 1710 | } |
afa0b07c | 1711 | |
1712 | if (!empty($op)) { | |
1713 | $params[$fieldName][$op] = $fieldValue; | |
1714 | } | |
1715 | else { | |
1716 | $params[$fieldName] = $fieldValue; | |
9bee5ea2 EM |
1717 | } |
1718 | } | |
1719 | ||
1720 | /** | |
9d32e6f7 EM |
1721 | * Convert date into BAO friendly date. |
1722 | * | |
1723 | * We accept 'whatever strtotime accepts' | |
9bee5ea2 EM |
1724 | * |
1725 | * @param string $dateValue | |
100fef9d | 1726 | * @param string $fieldName |
9bee5ea2 EM |
1727 | * @param $fieldType |
1728 | * | |
1729 | * @throws Exception | |
9bee5ea2 EM |
1730 | * @return mixed |
1731 | */ | |
1732 | function _civicrm_api3_getValidDate($dateValue, $fieldName, $fieldType) { | |
1733 | if (is_array($dateValue)) { | |
1734 | foreach ($dateValue as $key => $value) { | |
1735 | $dateValue[$key] = _civicrm_api3_getValidDate($value, $fieldName, $fieldType); | |
6a488035 | 1736 | } |
9bee5ea2 EM |
1737 | return $dateValue; |
1738 | } | |
1739 | if (strtotime($dateValue) === FALSE) { | |
1740 | throw new Exception($fieldName . " is not a valid date: " . $dateValue); | |
6a488035 | 1741 | } |
9bee5ea2 EM |
1742 | $format = ($fieldType == CRM_Utils_Type::T_DATE) ? 'Ymd000000' : 'YmdHis'; |
1743 | return CRM_Utils_Date::processDate($dateValue, NULL, FALSE, $format); | |
6a488035 | 1744 | } |
11e09c59 TO |
1745 | |
1746 | /** | |
6a488035 TO |
1747 | * Validate foreign constraint fields being passed into API. |
1748 | * | |
645ee340 | 1749 | * @param mixed $fieldValue |
cf470720 | 1750 | * @param string $fieldName |
7f1a780c | 1751 | * Unique name of field being checked. |
cf470720 TO |
1752 | * @param array $fieldInfo |
1753 | * Array of fields from getfields function. | |
7f1a780c | 1754 | * @param string $entity |
9d32e6f7 | 1755 | * |
645ee340 | 1756 | * @throws \API_Exception |
6a488035 | 1757 | */ |
7f1a780c | 1758 | function _civicrm_api3_validate_constraint($fieldValue, $fieldName, $fieldInfo, $entity) { |
971d41b1 | 1759 | $daoName = $fieldInfo['FKClassName']; |
7f1a780c | 1760 | $fieldInfo = [$fieldName => $fieldInfo]; |
1761 | $params = [$fieldName => $fieldValue]; | |
1762 | _civicrm_api3_validate_fields($entity, NULL, $params, $fieldInfo); | |
1763 | /* @var CRM_Core_DAO $dao*/ | |
971d41b1 | 1764 | $dao = new $daoName(); |
7f1a780c | 1765 | $dao->id = $params[$fieldName]; |
6a488035 TO |
1766 | $dao->selectAdd(); |
1767 | $dao->selectAdd('id'); | |
1768 | if (!$dao->find()) { | |
645ee340 | 1769 | throw new API_Exception("$fieldName is not valid : " . $fieldValue); |
6a488035 TO |
1770 | } |
1771 | } | |
1772 | ||
11e09c59 | 1773 | /** |
6a488035 TO |
1774 | * Validate foreign constraint fields being passed into API. |
1775 | * | |
cf470720 TO |
1776 | * @param array $params |
1777 | * Params from civicrm_api. | |
1778 | * @param string $fieldName | |
1779 | * Uniquename of field being checked. | |
9d32e6f7 | 1780 | * |
916b48b6 | 1781 | * @throws Exception |
6a488035 | 1782 | */ |
8adf88cf | 1783 | function _civicrm_api3_validate_unique_key(&$params, &$fieldName) { |
afa0b07c | 1784 | list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName); |
1785 | if (strpos($op, 'NULL') !== FALSE || strpos($op, 'EMPTY') !== FALSE) { | |
1786 | return; | |
1787 | } | |
cf8f0fff | 1788 | $existing = civicrm_api($params['entity'], 'get', [ |
7c31ae57 SL |
1789 | 'version' => $params['version'], |
1790 | $fieldName => $fieldValue, | |
1791 | ]); | |
6a488035 TO |
1792 | // an entry already exists for this unique field |
1793 | if ($existing['count'] == 1) { | |
1794 | // question - could this ever be a security issue? | |
446f0940 | 1795 | throw new API_Exception("Field: `$fieldName` must be unique. An conflicting entity already exists - id: " . $existing['id']); |
6a488035 TO |
1796 | } |
1797 | } | |
1798 | ||
1799 | /** | |
1800 | * Generic implementation of the "replace" action. | |
1801 | * | |
1802 | * Replace the old set of entities (matching some given keys) with a new set of | |
1803 | * entities (matching the same keys). | |
1804 | * | |
b081365f | 1805 | * @note This will verify that 'values' is present, but it does not directly verify |
6a488035 TO |
1806 | * any other parameters. |
1807 | * | |
cf470720 TO |
1808 | * @param string $entity |
1809 | * Entity name. | |
1810 | * @param array $params | |
1811 | * Params from civicrm_api, including:. | |
6a488035 | 1812 | * - 'values': an array of records to save |
9d32e6f7 EM |
1813 | * - all other items: keys which identify new/pre-existing records. |
1814 | * | |
26728d3f | 1815 | * @return array|int |
6a488035 TO |
1816 | */ |
1817 | function _civicrm_api3_generic_replace($entity, $params) { | |
1818 | ||
6a488035 TO |
1819 | $transaction = new CRM_Core_Transaction(); |
1820 | try { | |
1821 | if (!is_array($params['values'])) { | |
1822 | throw new Exception("Mandatory key(s) missing from params array: values"); | |
1823 | } | |
1824 | ||
1825 | // Extract the keys -- somewhat scary, don't think too hard about it | |
e4b4e33a | 1826 | $baseParams = _civicrm_api3_generic_replace_base_params($params); |
6a488035 TO |
1827 | |
1828 | // Lookup pre-existing records | |
1829 | $preexisting = civicrm_api($entity, 'get', $baseParams, $params); | |
1830 | if (civicrm_error($preexisting)) { | |
1831 | $transaction->rollback(); | |
1832 | return $preexisting; | |
1833 | } | |
1834 | ||
1835 | // Save the new/updated records | |
cf8f0fff | 1836 | $creates = []; |
6a488035 TO |
1837 | foreach ($params['values'] as $replacement) { |
1838 | // Sugar: Don't force clients to duplicate the 'key' data | |
1839 | $replacement = array_merge($baseParams, $replacement); | |
1840 | $action = (isset($replacement['id']) || isset($replacement[$entity . '_id'])) ? 'update' : 'create'; | |
1841 | $create = civicrm_api($entity, $action, $replacement); | |
1842 | if (civicrm_error($create)) { | |
1843 | $transaction->rollback(); | |
1844 | return $create; | |
1845 | } | |
1846 | foreach ($create['values'] as $entity_id => $entity_value) { | |
1847 | $creates[$entity_id] = $entity_value; | |
1848 | } | |
1849 | } | |
1850 | ||
1851 | // Remove stale records | |
1852 | $staleIDs = array_diff( | |
1853 | array_keys($preexisting['values']), | |
1854 | array_keys($creates) | |
1855 | ); | |
1856 | foreach ($staleIDs as $staleID) { | |
cf8f0fff | 1857 | $delete = civicrm_api($entity, 'delete', [ |
7c31ae57 SL |
1858 | 'version' => $params['version'], |
1859 | 'id' => $staleID, | |
1860 | ]); | |
6a488035 TO |
1861 | if (civicrm_error($delete)) { |
1862 | $transaction->rollback(); | |
1863 | return $delete; | |
1864 | } | |
1865 | } | |
1866 | ||
1867 | return civicrm_api3_create_success($creates, $params); | |
1868 | } | |
7c31ae57 | 1869 | catch (PEAR_Exception $e) { |
6a488035 TO |
1870 | $transaction->rollback(); |
1871 | return civicrm_api3_create_error($e->getMessage()); | |
1872 | } | |
7c31ae57 | 1873 | catch (Exception $e) { |
6a488035 TO |
1874 | $transaction->rollback(); |
1875 | return civicrm_api3_create_error($e->getMessage()); | |
1876 | } | |
1877 | } | |
1878 | ||
26728d3f | 1879 | /** |
9d32e6f7 EM |
1880 | * Replace base parameters. |
1881 | * | |
c490a46a | 1882 | * @param array $params |
26728d3f | 1883 | * |
9d32e6f7 | 1884 | * @return array |
26728d3f | 1885 | */ |
e4b4e33a TO |
1886 | function _civicrm_api3_generic_replace_base_params($params) { |
1887 | $baseParams = $params; | |
1888 | unset($baseParams['values']); | |
1889 | unset($baseParams['sequential']); | |
1890 | unset($baseParams['options']); | |
1891 | return $baseParams; | |
1892 | } | |
1893 | ||
11e09c59 | 1894 | /** |
9d32e6f7 | 1895 | * Returns fields allowable by api. |
26728d3f | 1896 | * |
cf470720 TO |
1897 | * @param $entity |
1898 | * String Entity to query. | |
1899 | * @param bool $unique | |
1900 | * Index by unique fields?. | |
26728d3f E |
1901 | * @param array $params |
1902 | * | |
1903 | * @return array | |
6a488035 | 1904 | */ |
cf8f0fff CW |
1905 | function _civicrm_api_get_fields($entity, $unique = FALSE, &$params = []) { |
1906 | $unsetIfEmpty = [ | |
9d32e6f7 EM |
1907 | 'dataPattern', |
1908 | 'headerPattern', | |
1909 | 'default', | |
1910 | 'export', | |
1911 | 'import', | |
cf8f0fff | 1912 | ]; |
6a488035 TO |
1913 | $dao = _civicrm_api3_get_DAO($entity); |
1914 | if (empty($dao)) { | |
cf8f0fff | 1915 | return []; |
6a488035 | 1916 | } |
6a488035 TO |
1917 | $d = new $dao(); |
1918 | $fields = $d->fields(); | |
95457d69 | 1919 | |
95457d69 | 1920 | foreach ($fields as $name => &$field) { |
5147800e CW |
1921 | // Denote as core field |
1922 | $field['is_core_field'] = TRUE; | |
1923 | // Set html attributes for text fields | |
95457d69 CW |
1924 | if (isset($field['html'])) { |
1925 | $field['html'] += (array) $d::makeAttribute($field); | |
1926 | } | |
1927 | } | |
1928 | ||
6a488035 TO |
1929 | // replace uniqueNames by the normal names as the key |
1930 | if (empty($unique)) { | |
fc6a6a51 | 1931 | foreach ($fields as $name => &$field) { |
6a488035 TO |
1932 | //getting rid of unused attributes |
1933 | foreach ($unsetIfEmpty as $attr) { | |
1934 | if (empty($field[$attr])) { | |
1935 | unset($field[$attr]); | |
1936 | } | |
1937 | } | |
1938 | if ($name == $field['name']) { | |
1939 | continue; | |
1940 | } | |
1941 | if (array_key_exists($field['name'], $fields)) { | |
1942 | $field['error'] = 'name conflict'; | |
1943 | // it should never happen, but better safe than sorry | |
1944 | continue; | |
1945 | } | |
1946 | $fields[$field['name']] = $field; | |
1947 | $fields[$field['name']]['uniqueName'] = $name; | |
1948 | unset($fields[$name]); | |
1949 | } | |
1950 | } | |
fc6a6a51 CW |
1951 | // Translate FKClassName to the corresponding api |
1952 | foreach ($fields as $name => &$field) { | |
1953 | if (!empty($field['FKClassName'])) { | |
1954 | $FKApi = CRM_Core_DAO_AllCoreTables::getBriefName($field['FKClassName']); | |
1955 | if ($FKApi) { | |
1956 | $field['FKApiName'] = $FKApi; | |
1957 | } | |
1958 | } | |
1959 | } | |
6a488035 TO |
1960 | $fields += _civicrm_api_get_custom_fields($entity, $params); |
1961 | return $fields; | |
1962 | } | |
1963 | ||
11e09c59 | 1964 | /** |
9d32e6f7 EM |
1965 | * Return an array of fields for a given entity. |
1966 | * | |
1967 | * This is the same as the BAO function but fields are prefixed with 'custom_' to represent api params. | |
1968 | * | |
645ee340 | 1969 | * @param $entity |
d0997921 | 1970 | * @param array $params |
9d32e6f7 | 1971 | * |
645ee340 | 1972 | * @return array |
6a488035 TO |
1973 | */ |
1974 | function _civicrm_api_get_custom_fields($entity, &$params) { | |
6a488035 | 1975 | $entity = _civicrm_api_get_camel_name($entity); |
18ec726b CW |
1976 | if ($entity == 'Contact') { |
1977 | // Use sub-type if available, otherwise "NULL" to fetch from all contact types | |
0400dfac | 1978 | $entity = CRM_Utils_Array::value('contact_type', $params); |
6a488035 | 1979 | } |
6a488035 TO |
1980 | $customfields = CRM_Core_BAO_CustomField::getFields($entity, |
1981 | FALSE, | |
1982 | FALSE, | |
18ec726b | 1983 | // we could / should probably test for other subtypes here - e.g. activity_type_id |
39cb3d7b | 1984 | CRM_Utils_Array::value('contact_sub_type', $params), |
6a488035 | 1985 | NULL, |
18ec726b | 1986 | FALSE, |
6a488035 TO |
1987 | FALSE, |
1988 | FALSE | |
1989 | ); | |
ddaac11c | 1990 | |
cf8f0fff | 1991 | $ret = []; |
6a488035 TO |
1992 | |
1993 | foreach ($customfields as $key => $value) { | |
a4c5e9a3 CW |
1994 | // Regular fields have a 'name' property |
1995 | $value['name'] = 'custom_' . $key; | |
3a8e9315 | 1996 | $value['title'] = $value['label']; |
8ad22b15 | 1997 | if ($value['data_type'] == 'Date' && CRM_Utils_Array::value('time_format', $value, 0) > 0) { |
1998 | $value['data_type'] = 'DateTime'; | |
1999 | } | |
2000 | $value['type'] = CRM_Utils_Array::value($value['data_type'], CRM_Core_BAO_CustomField::dataToType()); | |
ddaac11c | 2001 | $ret['custom_' . $key] = $value; |
6a488035 | 2002 | } |
ddaac11c | 2003 | return $ret; |
6a488035 | 2004 | } |
645ee340 | 2005 | |
11e09c59 | 2006 | /** |
9d32e6f7 EM |
2007 | * Fill params array with alternate (alias) values where a field has an alias and that is filled & the main field isn't. |
2008 | * | |
6a488035 TO |
2009 | * If multiple aliases the last takes precedence |
2010 | * | |
2011 | * Function also swaps unique fields for non-unique fields & vice versa. | |
9d32e6f7 | 2012 | * |
645ee340 EM |
2013 | * @param $apiRequest |
2014 | * @param $fields | |
6a488035 | 2015 | */ |
94359f7e | 2016 | function _civicrm_api3_swap_out_aliases(&$apiRequest, $fields) { |
2017 | foreach ($fields as $field => $values) { | |
6a488035 | 2018 | $uniqueName = CRM_Utils_Array::value('uniqueName', $values); |
a7488080 | 2019 | if (!empty($values['api.aliases'])) { |
6a488035 TO |
2020 | // if aliased field is not set we try to use field alias |
2021 | if (!isset($apiRequest['params'][$field])) { | |
2022 | foreach ($values['api.aliases'] as $alias) { | |
2023 | if (isset($apiRequest['params'][$alias])) { | |
2024 | $apiRequest['params'][$field] = $apiRequest['params'][$alias]; | |
2025 | } | |
2026 | //unset original field nb - need to be careful with this as it may bring inconsistencies | |
2027 | // out of the woodwork but will be implementing only as _spec function extended | |
2028 | unset($apiRequest['params'][$alias]); | |
2029 | } | |
2030 | } | |
2031 | } | |
8cc574cf | 2032 | if (!isset($apiRequest['params'][$field]) && !empty($values['name']) && $field != $values['name'] |
6a488035 TO |
2033 | && isset($apiRequest['params'][$values['name']]) |
2034 | ) { | |
2035 | $apiRequest['params'][$field] = $apiRequest['params'][$values['name']]; | |
2036 | // note that it would make sense to unset the original field here but tests need to be in place first | |
79b61cd0 | 2037 | if ($field != 'domain_version') { |
2038 | unset($apiRequest['params'][$values['name']]); | |
2039 | } | |
6a488035 TO |
2040 | } |
2041 | if (!isset($apiRequest['params'][$field]) | |
2042 | && $uniqueName | |
2043 | && $field != $uniqueName | |
2044 | && array_key_exists($uniqueName, $apiRequest['params']) | |
971d41b1 | 2045 | ) { |
6a488035 TO |
2046 | $apiRequest['params'][$field] = CRM_Utils_Array::value($values['uniqueName'], $apiRequest['params']); |
2047 | // note that it would make sense to unset the original field here but tests need to be in place first | |
2048 | } | |
2049 | } | |
2050 | ||
2051 | } | |
11e09c59 TO |
2052 | |
2053 | /** | |
6a488035 | 2054 | * Validate integer fields being passed into API. |
9d32e6f7 EM |
2055 | * |
2056 | * It currently converts the incoming value 'user_contact_id' into the id of the currently logged in user. | |
6a488035 | 2057 | * |
cf470720 TO |
2058 | * @param array $params |
2059 | * Params from civicrm_api. | |
2060 | * @param string $fieldName | |
2061 | * Uniquename of field being checked. | |
2062 | * @param array $fieldInfo | |
2063 | * Array of fields from getfields function. | |
5e436708 | 2064 | * @param string $entity |
9d32e6f7 | 2065 | * |
916b48b6 | 2066 | * @throws API_Exception |
6a488035 | 2067 | */ |
526e0834 | 2068 | function _civicrm_api3_validate_integer(&$params, $fieldName, &$fieldInfo, $entity) { |
afa0b07c | 2069 | list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName); |
2070 | if (strpos($op, 'NULL') !== FALSE || strpos($op, 'EMPTY') !== FALSE) { | |
2071 | return; | |
2072 | } | |
2073 | ||
80452d96 | 2074 | if (!empty($fieldValue) || $fieldValue === '0' || $fieldValue === 0) { |
46b6363c | 2075 | // if value = 'user_contact_id' (or similar), replace value with contact id |
3c151c70 | 2076 | if (!is_numeric($fieldValue) && is_scalar($fieldValue)) { |
2077 | $realContactId = _civicrm_api3_resolve_contactID($fieldValue); | |
17cb9f7f | 2078 | if ('unknown-user' === $realContactId) { |
cf8f0fff | 2079 | throw new API_Exception("\"$fieldName\" \"{$fieldValue}\" cannot be resolved to a contact ID", 2002, ['error_field' => $fieldName, "type" => "integer"]); |
971d41b1 CW |
2080 | } |
2081 | elseif (is_numeric($realContactId)) { | |
2fa797b9 | 2082 | $fieldValue = $realContactId; |
46b6363c | 2083 | } |
a98504a7 | 2084 | elseif (is_null($realContactId) && empty($fieldInfo['api.required']) && $fieldValue === 'user_contact_id') { |
c442f1b6 | 2085 | // If not mandatory this will be OK. If mandatory it should fail. |
2086 | $fieldValue = NULL; | |
2087 | } | |
6a488035 | 2088 | } |
6fa8a394 | 2089 | if (!empty($fieldInfo['pseudoconstant']) || !empty($fieldInfo['options'])) { |
cf8f0fff | 2090 | $additional_lookup_params = []; |
19381641 MH |
2091 | if (strtolower($entity) == 'address' && $fieldName == 'state_province_id') { |
2092 | $country_id = _civicrm_api3_resolve_country_id($params); | |
2093 | if (!empty($country_id)) { | |
2094 | $additional_lookup_params = ['country_id' => $country_id]; | |
2095 | } | |
eaf39b47 MH |
2096 | } |
2097 | _civicrm_api3_api_match_pseudoconstant($fieldValue, $entity, $fieldName, $fieldInfo, $op, $additional_lookup_params); | |
6a488035 TO |
2098 | } |
2099 | ||
283f988c | 2100 | // After swapping options, ensure we have an integer(s) |
3c151c70 | 2101 | foreach ((array) ($fieldValue) as $value) { |
c442f1b6 | 2102 | if ($value && !is_numeric($value) && $value !== 'null' && $value !== NULL && !is_array($value)) { |
cf8f0fff | 2103 | throw new API_Exception("$fieldName is not a valid integer", 2001, ['error_field' => $fieldName, "type" => "integer"]); |
283f988c | 2104 | } |
6fa8a394 CW |
2105 | } |
2106 | ||
2107 | // Check our field length | |
971d41b1 | 2108 | if (is_string($fieldValue) && !empty($fieldInfo['maxlength']) && strlen($fieldValue) > $fieldInfo['maxlength'] |
48a89be3 | 2109 | ) { |
79d7553f | 2110 | throw new API_Exception($fieldValue . " is " . strlen($fieldValue) . " characters - longer than $fieldName length" . $fieldInfo['maxlength'] . ' characters', |
cf8f0fff | 2111 | 2100, ['field' => $fieldName, "max_length" => $fieldInfo['maxlength']] |
6a488035 TO |
2112 | ); |
2113 | } | |
2114 | } | |
2fa797b9 | 2115 | |
2116 | if (!empty($op)) { | |
2117 | $params[$fieldName][$op] = $fieldValue; | |
2118 | } | |
2119 | else { | |
2120 | $params[$fieldName] = $fieldValue; | |
2121 | } | |
6a488035 TO |
2122 | } |
2123 | ||
19381641 MH |
2124 | /** |
2125 | * Helper function to determine country_id given the myriad of values for country_id or country that are supported | |
2126 | * @param $params | |
2127 | * | |
2128 | * @return int|null | |
2129 | */ | |
2130 | function _civicrm_api3_resolve_country_id($params) { | |
2131 | if (!empty($params['country_id'])) { | |
2132 | if (is_numeric($params['country_id'])) { | |
2133 | $country_id = $params['country_id']; | |
2134 | } | |
2135 | else { | |
2136 | $country = new CRM_Core_DAO_Country(); | |
2137 | $country->name = $params['country_id']; | |
2138 | if (!$country->find(TRUE)) { | |
2139 | $country->name = NULL; | |
2140 | $country->iso_code = $params['country_id']; | |
2141 | $country->find(TRUE); | |
2142 | } | |
2143 | if (!empty($country->id)) { | |
2144 | $country_id = $country->id; | |
2145 | } | |
2146 | } | |
2147 | } | |
2148 | elseif (!empty($params['country'])) { | |
2149 | if (is_numeric($params['country'])) { | |
2150 | $country_id = $params['country']; | |
2151 | } | |
2152 | else { | |
2153 | $country = new CRM_Core_DAO_Country(); | |
2154 | $country->name = $params['country']; | |
2155 | if (!$country->find(TRUE)) { | |
2156 | $country->name = NULL; | |
2157 | $country->iso_code = $params['country']; | |
2158 | $country->find(TRUE); | |
2159 | } | |
2160 | if (!empty($country->id)) { | |
2161 | $country_id = $country->id; | |
2162 | } | |
2163 | } | |
2164 | } | |
2165 | return !empty($country_id) ? $country_id : NULL; | |
2166 | } | |
2167 | ||
46b6363c | 2168 | /** |
9d32e6f7 | 2169 | * Determine a contact ID using a string expression. |
46b6363c | 2170 | * |
cf470720 TO |
2171 | * @param string $contactIdExpr |
2172 | * E.g. "user_contact_id" or "@user:username". | |
9d32e6f7 | 2173 | * |
e97c66ff | 2174 | * @return int|null|'unknown-user' |
2175 | * @throws \CRM_Core_Exception | |
46b6363c | 2176 | */ |
37fa58b0 | 2177 | function _civicrm_api3_resolve_contactID($contactIdExpr) { |
9d32e6f7 | 2178 | // If value = 'user_contact_id' replace value with logged in user id. |
46b6363c | 2179 | if ($contactIdExpr == "user_contact_id") { |
bb341097 EM |
2180 | return CRM_Core_Session::getLoggedInContactID(); |
2181 | } | |
2182 | elseif (preg_match('/^@user:(.*)$/', $contactIdExpr, $matches)) { | |
46b6363c TO |
2183 | $config = CRM_Core_Config::singleton(); |
2184 | ||
2185 | $ufID = $config->userSystem->getUfId($matches[1]); | |
2186 | if (!$ufID) { | |
17cb9f7f | 2187 | return 'unknown-user'; |
46b6363c TO |
2188 | } |
2189 | ||
2190 | $contactID = CRM_Core_BAO_UFMatch::getContactId($ufID); | |
17cb9f7f TO |
2191 | if (!$contactID) { |
2192 | return 'unknown-user'; | |
46b6363c TO |
2193 | } |
2194 | ||
2195 | return $contactID; | |
2196 | } | |
31fd7b1e | 2197 | return NULL; |
46b6363c TO |
2198 | } |
2199 | ||
26728d3f | 2200 | /** |
9d32e6f7 EM |
2201 | * Validate html (check for scripting attack). |
2202 | * | |
5e436708 EM |
2203 | * @param array $params |
2204 | * @param string $fieldName | |
2205 | * @param array $fieldInfo | |
26728d3f E |
2206 | * |
2207 | * @throws API_Exception | |
2208 | */ | |
5e436708 | 2209 | function _civicrm_api3_validate_html(&$params, &$fieldName, $fieldInfo) { |
afa0b07c | 2210 | list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName); |
2211 | if (strpos($op, 'NULL') || strpos($op, 'EMPTY')) { | |
2212 | return; | |
2213 | } | |
3c151c70 | 2214 | if ($fieldValue) { |
2215 | if (!CRM_Utils_Rule::xssString($fieldValue)) { | |
cf8f0fff | 2216 | throw new API_Exception('Input contains illegal SCRIPT tag.', ["field" => $fieldName, "error_code" => "xss"]); |
6a488035 TO |
2217 | } |
2218 | } | |
2219 | } | |
2220 | ||
11e09c59 | 2221 | /** |
6a488035 | 2222 | * Validate string fields being passed into API. |
9d32e6f7 | 2223 | * |
cf470720 TO |
2224 | * @param array $params |
2225 | * Params from civicrm_api. | |
2226 | * @param string $fieldName | |
2227 | * Uniquename of field being checked. | |
2228 | * @param array $fieldInfo | |
2229 | * Array of fields from getfields function. | |
5e436708 | 2230 | * @param string $entity |
9d32e6f7 | 2231 | * |
916b48b6 VU |
2232 | * @throws API_Exception |
2233 | * @throws Exception | |
6a488035 | 2234 | */ |
70f7ba9e | 2235 | function _civicrm_api3_validate_string(&$params, &$fieldName, &$fieldInfo, $entity) { |
cbfe5232 | 2236 | list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName, 'String'); |
02ea3d64 | 2237 | if (strpos($op, 'NULL') !== FALSE || strpos($op, 'EMPTY') !== FALSE || CRM_Utils_System::isNull($fieldValue)) { |
afa0b07c | 2238 | return; |
2239 | } | |
02ea3d64 | 2240 | |
48a89be3 | 2241 | if (!is_array($fieldValue)) { |
3c151c70 | 2242 | $fieldValue = (string) $fieldValue; |
69c1fac4 | 2243 | } |
4b02a1c4 | 2244 | |
3c151c70 | 2245 | if ($fieldValue) { |
4b02a1c4 | 2246 | foreach ((array) $fieldValue as $key => $value) { |
2247 | foreach ([$fieldValue, $key, $value] as $input) { | |
2248 | if (!CRM_Utils_Rule::xssString($input)) { | |
2249 | throw new Exception('Input contains illegal SCRIPT tag.'); | |
2250 | } | |
02ea3d64 | 2251 | } |
2252 | if ($fieldName == 'currency') { | |
2253 | //When using IN operator $fieldValue is a array of currency codes | |
2254 | if (!CRM_Utils_Rule::currencyCode($value)) { | |
7d543448 | 2255 | throw new Exception("Currency not a valid code: $currency"); |
3c151c70 | 2256 | } |
6a488035 TO |
2257 | } |
2258 | } | |
6a488035 | 2259 | } |
7d543448 | 2260 | if (!empty($fieldInfo['pseudoconstant']) || !empty($fieldInfo['options'])) { |
415d9abb | 2261 | _civicrm_api3_api_match_pseudoconstant($fieldValue, $entity, $fieldName, $fieldInfo, $op); |
7d543448 | 2262 | } |
2263 | // Check our field length | |
2264 | elseif (is_string($fieldValue) && !empty($fieldInfo['maxlength']) && strlen(utf8_decode($fieldValue)) > $fieldInfo['maxlength']) { | |
2265 | throw new API_Exception("Value for $fieldName is " . strlen(utf8_decode($value)) . " characters - This field has a maxlength of {$fieldInfo['maxlength']} characters.", | |
cf8f0fff | 2266 | 2100, ['field' => $fieldName] |
7d543448 | 2267 | ); |
2268 | } | |
2fa797b9 | 2269 | |
2270 | if (!empty($op)) { | |
2271 | $params[$fieldName][$op] = $fieldValue; | |
2272 | } | |
2273 | else { | |
2274 | $params[$fieldName] = $fieldValue; | |
6a488035 TO |
2275 | } |
2276 | } | |
70f7ba9e CW |
2277 | |
2278 | /** | |
9d32e6f7 | 2279 | * Validate & swap out any pseudoconstants / options. |
70f7ba9e | 2280 | * |
645ee340 EM |
2281 | * @param mixed $fieldValue |
2282 | * @param string $entity : api entity name | |
2283 | * @param string $fieldName : field name used in api call (not necessarily the canonical name) | |
2284 | * @param array $fieldInfo : getfields meta-data | |
415d9abb | 2285 | * @param string $op |
eaf39b47 | 2286 | * @param array $additional_lookup_params |
9d32e6f7 | 2287 | * |
645ee340 | 2288 | * @throws \API_Exception |
70f7ba9e | 2289 | */ |
cf8f0fff CW |
2290 | function _civicrm_api3_api_match_pseudoconstant(&$fieldValue, $entity, $fieldName, $fieldInfo, $op = '=', $additional_lookup_params = []) { |
2291 | if (in_array($op, ['>', '<', '>=', '<=', 'LIKE', 'NOT LIKE'])) { | |
415d9abb CW |
2292 | return; |
2293 | } | |
2294 | ||
6fa8a394 | 2295 | $options = CRM_Utils_Array::value('options', $fieldInfo); |
08fe8c7e | 2296 | |
6fa8a394 | 2297 | if (!$options) { |
22e263ad | 2298 | if (strtolower($entity) == 'profile' && !empty($fieldInfo['entity'])) { |
9d32e6f7 | 2299 | // We need to get the options from the entity the field relates to. |
94359f7e | 2300 | $entity = $fieldInfo['entity']; |
2301 | } | |
eaf39b47 | 2302 | $options_lookup_params = [ |
9d32e6f7 EM |
2303 | 'version' => 3, |
2304 | 'field' => $fieldInfo['name'], | |
2305 | 'context' => 'validate', | |
eaf39b47 MH |
2306 | ]; |
2307 | if (!empty($additional_lookup_params)) { | |
2308 | $options_lookup_params = array_merge($additional_lookup_params, $options_lookup_params); | |
2309 | } | |
2310 | $options = civicrm_api($entity, 'getoptions', $options_lookup_params); | |
2311 | ||
cf8f0fff | 2312 | $options = CRM_Utils_Array::value('values', $options, []); |
6fa8a394 | 2313 | } |
70f7ba9e | 2314 | |
9d32e6f7 | 2315 | // If passed a value-separated string, explode to an array, then re-implode after matching values. |
70f7ba9e | 2316 | $implode = FALSE; |
3c151c70 | 2317 | if (is_string($fieldValue) && strpos($fieldValue, CRM_Core_DAO::VALUE_SEPARATOR) !== FALSE) { |
2318 | $fieldValue = CRM_Utils_Array::explodePadded($fieldValue); | |
70f7ba9e CW |
2319 | $implode = TRUE; |
2320 | } | |
9d32e6f7 | 2321 | // If passed multiple options, validate each. |
3c151c70 | 2322 | if (is_array($fieldValue)) { |
2323 | foreach ($fieldValue as &$value) { | |
736f9c2d | 2324 | if (!is_array($value)) { |
57369d23 | 2325 | _civicrm_api3_api_match_pseudoconstant_value($value, $options, $fieldName, CRM_Utils_Array::value('api.required', $fieldInfo)); |
736f9c2d | 2326 | } |
70f7ba9e CW |
2327 | } |
2328 | // TODO: unwrap the call to implodePadded from the conditional and do it always | |
2329 | // need to verify that this is safe and doesn't break anything though. | |
2330 | // Better yet would be to leave it as an array and ensure that every dao/bao can handle array input | |
2331 | if ($implode) { | |
3c151c70 | 2332 | CRM_Utils_Array::implodePadded($fieldValue); |
70f7ba9e CW |
2333 | } |
2334 | } | |
2335 | else { | |
57369d23 | 2336 | _civicrm_api3_api_match_pseudoconstant_value($fieldValue, $options, $fieldName, CRM_Utils_Array::value('api.required', $fieldInfo)); |
70f7ba9e CW |
2337 | } |
2338 | } | |
2339 | ||
2340 | /** | |
9d32e6f7 | 2341 | * Validate & swap a single option value for a field. |
70f7ba9e | 2342 | * |
971d41b1 CW |
2343 | * @param string $value field value |
2344 | * @param array $options array of options for this field | |
2345 | * @param string $fieldName field name used in api call (not necessarily the canonical name) | |
57369d23 | 2346 | * @param bool $isRequired |
2347 | * Is this a required field or is 'null' an acceptable option. We allow 'null' last | |
2348 | * in case we have the weird situation of it being a valid option in which case our | |
2349 | * brains will probably explode. | |
9d32e6f7 | 2350 | * |
916b48b6 | 2351 | * @throws API_Exception |
70f7ba9e | 2352 | */ |
57369d23 | 2353 | function _civicrm_api3_api_match_pseudoconstant_value(&$value, $options, $fieldName, $isRequired) { |
70f7ba9e | 2354 | // If option is a key, no need to translate |
08fe8c7e | 2355 | // or if no options are avaiable for pseudoconstant 'table' property |
2356 | if (array_key_exists($value, $options) || !$options) { | |
70f7ba9e CW |
2357 | return; |
2358 | } | |
70f7ba9e | 2359 | |
75c4fcec CW |
2360 | // Hack for Profile formatting fields |
2361 | if ($fieldName === 'field_name' && (strpos($value, 'formatting') === 0)) { | |
2362 | return; | |
2363 | } | |
2364 | ||
a4c5e9a3 | 2365 | // Translate value into key |
80452d96 CW |
2366 | // Cast $value to string to avoid a bug in array_search |
2367 | $newValue = array_search((string) $value, $options); | |
a4c5e9a3 CW |
2368 | if ($newValue !== FALSE) { |
2369 | $value = $newValue; | |
2370 | return; | |
2371 | } | |
70f7ba9e | 2372 | // Case-insensitive matching |
80085473 | 2373 | $newValue = strtolower($value); |
70f7ba9e | 2374 | $options = array_map("strtolower", $options); |
80085473 CW |
2375 | $newValue = array_search($newValue, $options); |
2376 | if ($newValue === FALSE) { | |
57369d23 | 2377 | if ($value === 'null' && !$isRequired) { |
2378 | // CiviMagic syntax for Nulling out the field - let it through. | |
2379 | return; | |
2380 | } | |
cf8f0fff | 2381 | throw new API_Exception("'$value' is not a valid option for field $fieldName", 2001, ['error_field' => $fieldName]); |
70f7ba9e | 2382 | } |
80085473 | 2383 | $value = $newValue; |
70f7ba9e CW |
2384 | } |
2385 | ||
2386 | /** | |
9d32e6f7 | 2387 | * Returns the canonical name of a field. |
70f7ba9e | 2388 | * |
cf470720 | 2389 | * @param $entity |
16b10e64 | 2390 | * api entity name (string should already be standardized - no camelCase). |
cf470720 | 2391 | * @param $fieldName |
16b10e64 | 2392 | * any variation of a field's name (name, unique_name, api.alias). |
77b97be7 | 2393 | * |
2b28667f | 2394 | * @param string $action |
2395 | * | |
72b3a70c | 2396 | * @return bool|string |
2b28667f | 2397 | * FieldName or FALSE if the field does not exist |
70f7ba9e | 2398 | */ |
985f4890 | 2399 | function _civicrm_api3_api_resolve_alias($entity, $fieldName, $action = 'create') { |
26a700db CW |
2400 | if (!$fieldName) { |
2401 | return FALSE; | |
2402 | } | |
a38a89fc | 2403 | if (strpos($fieldName, 'custom_') === 0 && is_numeric($fieldName[7])) { |
a4c5e9a3 CW |
2404 | return $fieldName; |
2405 | } | |
e65c2445 | 2406 | if ($fieldName == _civicrm_api_get_entity_name_from_camel($entity) . '_id') { |
a4c5e9a3 CW |
2407 | return 'id'; |
2408 | } | |
cf8f0fff | 2409 | $result = civicrm_api($entity, 'getfields', [ |
70f7ba9e | 2410 | 'version' => 3, |
985f4890 | 2411 | 'action' => $action, |
cf8f0fff | 2412 | ]); |
70f7ba9e | 2413 | $meta = $result['values']; |
e354351f | 2414 | if (!isset($meta[$fieldName]['name']) && isset($meta[$fieldName . '_id'])) { |
2415 | $fieldName = $fieldName . '_id'; | |
2416 | } | |
70f7ba9e CW |
2417 | if (isset($meta[$fieldName])) { |
2418 | return $meta[$fieldName]['name']; | |
2419 | } | |
70f7ba9e | 2420 | foreach ($meta as $info) { |
07945b3c | 2421 | if ($fieldName == $info['name'] || $fieldName == CRM_Utils_Array::value('uniqueName', $info)) { |
70f7ba9e CW |
2422 | return $info['name']; |
2423 | } | |
cf8f0fff | 2424 | if (array_search($fieldName, CRM_Utils_Array::value('api.aliases', $info, [])) !== FALSE) { |
70f7ba9e CW |
2425 | return $info['name']; |
2426 | } | |
2427 | } | |
985f4890 CW |
2428 | // Create didn't work, try with get |
2429 | if ($action == 'create') { | |
2430 | return _civicrm_api3_api_resolve_alias($entity, $fieldName, 'get'); | |
2431 | } | |
70f7ba9e CW |
2432 | return FALSE; |
2433 | } | |
a14e9d08 CW |
2434 | |
2435 | /** | |
9d32e6f7 EM |
2436 | * Check if the function is deprecated. |
2437 | * | |
a14e9d08 CW |
2438 | * @param string $entity |
2439 | * @param array $result | |
9d32e6f7 | 2440 | * |
15cbe793 | 2441 | * @return string|array|null |
a14e9d08 | 2442 | */ |
cf8f0fff | 2443 | function _civicrm_api3_deprecation_check($entity, $result = []) { |
15cbe793 | 2444 | if ($entity) { |
4846df91 CW |
2445 | $lowercase_entity = _civicrm_api_get_entity_name_from_camel($entity); |
2446 | $fnName = "_civicrm_api3_{$lowercase_entity}_deprecation"; | |
15cbe793 CW |
2447 | if (function_exists($fnName)) { |
2448 | return $fnName($result); | |
2449 | } | |
a14e9d08 CW |
2450 | } |
2451 | } | |
afa0b07c | 2452 | |
2453 | /** | |
9d32e6f7 EM |
2454 | * Get the actual field value. |
2455 | * | |
afa0b07c | 2456 | * In some case $params[$fieldName] holds Array value in this format Array([operator] => [value]) |
cbfe5232 | 2457 | * So this function returns the actual field value. |
afa0b07c | 2458 | * |
2459 | * @param array $params | |
2460 | * @param string $fieldName | |
cbfe5232 | 2461 | * @param string $type |
9d32e6f7 | 2462 | * |
971d41b1 | 2463 | * @return mixed |
afa0b07c | 2464 | */ |
cbfe5232 | 2465 | function _civicrm_api3_field_value_check(&$params, $fieldName, $type = NULL) { |
afa0b07c | 2466 | $fieldValue = CRM_Utils_Array::value($fieldName, $params); |
2467 | $op = NULL; | |
2468 | ||
cbfe5232 | 2469 | if (!empty($fieldValue) && is_array($fieldValue) && |
2470 | (array_search(key($fieldValue), CRM_Core_DAO::acceptedSQLOperators()) || | |
2471 | $type == 'String' && strstr(key($fieldValue), 'EMPTY')) | |
2472 | ) { | |
afa0b07c | 2473 | $op = key($fieldValue); |
2474 | $fieldValue = CRM_Utils_Array::value($op, $fieldValue); | |
2475 | } | |
cf8f0fff | 2476 | return [$fieldValue, $op]; |
afa0b07c | 2477 | } |
5bc7c754 TO |
2478 | |
2479 | /** | |
a066deea TO |
2480 | * A generic "get" API based on simple array data. This is comparable to |
2481 | * _civicrm_api3_basic_get but does not use DAO/BAO. This is useful for | |
2482 | * small/mid-size data loaded from external JSON or XML documents. | |
5bc7c754 | 2483 | * |
2b28667f | 2484 | * @param $entity |
5bc7c754 TO |
2485 | * @param array $params |
2486 | * API parameters. | |
2487 | * @param array $records | |
2488 | * List of all records. | |
2489 | * @param string $idCol | |
2490 | * The property which defines the ID of a record | |
b030796f | 2491 | * @param array $filterableFields |
5bc7c754 | 2492 | * List of filterable fields. |
2b28667f | 2493 | * |
5bc7c754 | 2494 | * @return array |
2b28667f | 2495 | * @throws \API_Exception |
5bc7c754 | 2496 | */ |
b030796f | 2497 | function _civicrm_api3_basic_array_get($entity, $params, $records, $idCol, $filterableFields) { |
5bc7c754 TO |
2498 | $options = _civicrm_api3_get_options_from_params($params, TRUE, $entity, 'get'); |
2499 | // TODO // $sort = CRM_Utils_Array::value('sort', $options, NULL); | |
2500 | $offset = CRM_Utils_Array::value('offset', $options); | |
2501 | $limit = CRM_Utils_Array::value('limit', $options); | |
2502 | ||
cf8f0fff | 2503 | $matches = []; |
5bc7c754 TO |
2504 | |
2505 | $currentOffset = 0; | |
2506 | foreach ($records as $record) { | |
2507 | if ($idCol != 'id') { | |
2508 | $record['id'] = $record[$idCol]; | |
2509 | } | |
2510 | $match = TRUE; | |
2511 | foreach ($params as $k => $v) { | |
a066deea TO |
2512 | if ($k == 'id') { |
2513 | $k = $idCol; | |
2514 | } | |
b030796f | 2515 | if (in_array($k, $filterableFields) && $record[$k] != $v) { |
5bc7c754 TO |
2516 | $match = FALSE; |
2517 | break; | |
2518 | } | |
2519 | } | |
2520 | if ($match) { | |
2521 | if ($currentOffset >= $offset) { | |
2522 | $matches[$record[$idCol]] = $record; | |
2523 | } | |
2524 | if ($limit && count($matches) >= $limit) { | |
2525 | break; | |
2526 | } | |
2527 | $currentOffset++; | |
2528 | } | |
2529 | } | |
2530 | ||
cf8f0fff | 2531 | $return = CRM_Utils_Array::value('return', $options, []); |
5bc7c754 TO |
2532 | if (!empty($return)) { |
2533 | $return['id'] = 1; | |
2534 | $matches = CRM_Utils_Array::filterColumns($matches, array_keys($return)); | |
2535 | } | |
2536 | ||
2537 | return civicrm_api3_create_success($matches, $params); | |
2538 | } | |
db83e3a3 CW |
2539 | |
2540 | /** | |
2541 | * @param string $bao_name | |
2542 | * @param array $params | |
2543 | * @throws \Civi\API\Exception\UnauthorizedException | |
2544 | */ | |
2545 | function _civicrm_api3_check_edit_permissions($bao_name, $params) { | |
2546 | // For lack of something more clever, here's a whitelist of entities whos permissions | |
2547 | // are inherited from a contact record. | |
2548 | // Note, when adding here, also remember to modify _civicrm_api3_permissions() | |
cf8f0fff | 2549 | $contactEntities = [ |
db83e3a3 CW |
2550 | 'CRM_Core_BAO_Email', |
2551 | 'CRM_Core_BAO_Phone', | |
2552 | 'CRM_Core_BAO_Address', | |
2553 | 'CRM_Core_BAO_IM', | |
2554 | 'CRM_Core_BAO_Website', | |
1c2ea456 | 2555 | 'CRM_Core_BAO_OpenID', |
cf8f0fff | 2556 | ]; |
db83e3a3 CW |
2557 | if (!empty($params['check_permissions']) && in_array($bao_name, $contactEntities)) { |
2558 | $cid = !empty($params['contact_id']) ? $params['contact_id'] : CRM_Core_DAO::getFieldValue($bao_name, $params['id'], 'contact_id'); | |
2559 | if (!CRM_Contact_BAO_Contact_Permission::allow($cid, CRM_Core_Permission::EDIT)) { | |
2560 | throw new \Civi\API\Exception\UnauthorizedException('Permission denied to modify contact record'); | |
2561 | } | |
2562 | } | |
2563 | } | |
2fc6d711 SL |
2564 | |
2565 | /** | |
2566 | * Check if an entity has been modified since the last known modified_date | |
a22a5119 | 2567 | * |
2fc6d711 SL |
2568 | * @param string $modifiedDate Last knowm modified_date |
2569 | * @param int $id Id of record to check | |
2570 | * @param string $entity API Entity | |
a22a5119 | 2571 | * |
2fc6d711 | 2572 | * @return bool |
a22a5119 | 2573 | * @throws \CiviCRM_API3_Exception |
2fc6d711 SL |
2574 | */ |
2575 | function _civicrm_api3_compare_timestamps($modifiedDate, $id, $entity) { | |
cf8f0fff | 2576 | $currentDbInfo = civicrm_api3($entity, 'getsingle', ['id' => $id]); |
2fc6d711 SL |
2577 | if (strtotime($currentDbInfo['modified_date']) <= strtotime($modifiedDate)) { |
2578 | return TRUE; | |
2579 | } | |
2580 | return FALSE; | |
2581 | } |