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