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