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