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