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