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