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