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