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