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