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