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