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