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