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