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