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