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