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