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