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