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