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