3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.4 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
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. |
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. |
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 +--------------------------------------------------------------------+
29 * File for CiviCRM APIv3 utilitity functions
31 * @package CiviCRM_APIv3
32 * @subpackage API_utils
34 * @copyright CiviCRM LLC (c) 2004-2013
35 * @version $Id: utils.php 30879 2010-11-22 15:45:55Z shot $
40 * Initialize CiviCRM - should be run at the start of each API function
42 function _civicrm_api3_initialize() {
43 require_once 'CRM/Core/ClassLoader.php';
44 CRM_Core_ClassLoader
::singleton()->register();
45 CRM_Core_Config
::singleton();
49 * Wrapper Function for civicrm_verify_mandatory to make it simple to pass either / or fields for checking
51 * @param array $params array of fields to checkl
52 * @param array $daoName string DAO to check for required fields (create functions only)
53 * @param array $keyoptions list of required fields options. One of the options is required
55 * @return null or throws error if there the required fields not present
58 function civicrm_api3_verify_one_mandatory($params, $daoName = NULL, $keyoptions = array(
60 $keys = array(array());
61 foreach ($keyoptions as $key) {
64 civicrm_api3_verify_mandatory($params, $daoName, $keys);
68 * Function to check mandatory fields are included
70 * @param array $params array of fields to check
71 * @param array $daoName string DAO to check for required fields (create functions only)
72 * @param array $keys list of required fields. A value can be an array denoting that either this or that is required.
73 * @param bool $verifyDAO
75 * @throws API_Exception
76 * @return null or throws error if there the required fields not present
78 * @todo see notes on _civicrm_api3_check_required_fields regarding removing $daoName param
80 function civicrm_api3_verify_mandatory($params, $daoName = NULL, $keys = array(
81 ), $verifyDAO = TRUE) {
84 if ($daoName != NULL && $verifyDAO && empty($params['id'])) {
85 $unmatched = _civicrm_api3_check_required_fields($params, $daoName, TRUE);
86 if (!is_array($unmatched)) {
91 if (!empty($params['id'])) {
92 $keys = array('version');
95 if (!in_array('version', $keys)) {
96 // required from v3 onwards
100 foreach ($keys as $key) {
101 if (is_array($key)) {
103 $optionset = array();
104 foreach ($key as $subkey) {
105 if (!array_key_exists($subkey, $params) ||
empty($params[$subkey])) {
106 $optionset[] = $subkey;
109 // as long as there is one match then we don't need to rtn anything
113 if (empty($match) && !empty($optionset)) {
114 $unmatched[] = "one of (" . implode(", ", $optionset) . ")";
118 // Disallow empty values except for the number zero.
119 // TODO: create a utility for this since it's needed in many places
120 if (!array_key_exists($key, $params) ||
(empty($params[$key]) && $params[$key] !== 0 && $params[$key] !== '0')) {
125 if (!empty($unmatched)) {
126 throw new API_Exception("Mandatory key(s) missing from params array: " . implode(", ", $unmatched),"mandatory_missing",array("fields"=>$unmatched));
132 * @param <type> $data
134 * @param object $dao DAO / BAO object to be freed here
136 * @throws API_Exception
137 * @return array <type>
139 function civicrm_api3_create_error($msg, $data = array(), &$dao = NULL) {
140 //fix me - $dao should be param 4 & 3 should be $apiRequest
141 if (is_object($dao)) {
145 if (is_array($dao)) {
146 if ($msg == 'DB Error: constraint violation' ||
substr($msg, 0,9) == 'DB Error:' ||
$msg == 'DB Error: already exists') {
148 $fields = _civicrm_api3_api_getfields($dao);
149 _civicrm_api3_validate_fields($dao['entity'], $dao['action'], $dao['params'], $fields, TRUE);
151 catch(Exception
$e) {
152 $msg = $e->getMessage();
156 $data['is_error'] = 1;
157 $data['error_message'] = $msg;
158 // we will show sql to privelledged user only (not sure of a specific
159 // security hole here but seems sensible - perhaps should apply to the trace as well?
160 if(isset($data['sql']) && CRM_Core_Permission
::check('Administer CiviCRM')) {
161 $data['debug_information'] = $data['sql'];
163 if (is_array($dao) && isset($dao['params']) && is_array($dao['params']) && CRM_Utils_Array
::value('api.has_parent', $dao['params'])) {
164 $errorCode = empty($data['error_code']) ?
'chained_api_failed' : $data['error_code'];
165 throw new API_Exception('Error in call to ' . $dao['entity'] . '_' . $dao['action'] . ' : ' . $msg, $errorCode, $data);
171 * Format array in result output styple
173 * @param array $values values generated by API operation (the result)
174 * @param array $params parameters passed into API call
175 * @param string $entity the entity being acted on
176 * @param string $action the action passed to the API
177 * @param object $dao DAO object to be freed here
178 * @param array $extraReturnValues additional values to be added to top level of result array(
179 * - this param is currently used for legacy behaviour support
181 * @return array $result
183 function civicrm_api3_create_success($values = 1, $params = array(
184 ), $entity = NULL, $action = NULL, &$dao = NULL, $extraReturnValues = array()) {
186 $result['is_error'] = 0;
187 //lets set the ['id'] field if it's not set & we know what the entity is
188 if (is_array($values) && !empty($entity)) {
189 foreach ($values as $key => $item) {
190 if (empty($item['id']) && !empty($item[$entity . "_id"])) {
191 $values[$key]['id'] = $item[$entity . "_id"];
193 if(!empty($item['financial_type_id'])){
194 //4.3 legacy handling
195 $values[$key]['contribution_type_id'] = $item['financial_type_id'];
197 if(!empty($item['next_sched_contribution_date'])){
198 // 4.4 legacy handling
199 $values[$key]['next_sched_contribution'] = $item['next_sched_contribution_date'];
204 if (is_array($params) && !empty($params['debug'])) {
205 if (is_string($action) && $action != 'getfields') {
206 $apiFields = civicrm_api($entity, 'getfields', array('version' => 3, 'action' => $action) +
$params);
208 elseif ($action != 'getfields') {
209 $apiFields = civicrm_api($entity, 'getfields', array('version' => 3) +
$params);
215 $allFields = array();
216 if ($action != 'getfields' && is_array($apiFields) && is_array(CRM_Utils_Array
::value('values', $apiFields))) {
217 $allFields = array_keys($apiFields['values']);
219 $paramFields = array_keys($params);
220 $undefined = array_diff($paramFields, $allFields, array_keys($_COOKIE), array('action', 'entity', 'debug', 'version', 'check_permissions', 'IDS_request_uri', 'IDS_user_agent', 'return', 'sequential', 'rowCount', 'option_offset', 'option_limit', 'custom', 'option_sort', 'options'));
222 $result['undefined_fields'] = array_merge($undefined);
225 if (is_object($dao)) {
229 $result['version'] = 3;
230 if (is_array($values)) {
231 $result['count'] = (int) count($values);
233 // Convert value-separated strings to array
234 _civicrm_api3_separate_values($values);
236 if ($result['count'] == 1) {
237 list($result['id']) = array_keys($values);
239 elseif (!empty($values['id']) && is_int($values['id'])) {
240 $result['id'] = $values['id'];
244 $result['count'] = !empty($values) ?
1 : 0;
247 if (is_array($values) && isset($params['sequential']) &&
248 $params['sequential'] == 1
250 $result['values'] = array_values($values);
253 $result['values'] = $values;
255 if(!empty($params['options']['metadata'])) {
256 // we've made metadata an array but only supporting 'fields' atm
257 if(in_array('fields', $params['options']['metadata'])) {
258 $fields = civicrm_api3($entity, 'getfields', array('action' => $action));
259 $result['metadata']['fields'] = $fields['values'];
262 return array_merge($result, $extraReturnValues);
266 * Load the DAO of the entity
268 function _civicrm_api3_load_DAO($entity) {
269 $dao = _civicrm_api3_get_DAO($entity);
278 * Function to return the DAO of the function or Entity
279 * @param String $name either a function of the api (civicrm_{entity}_create or the entity name
280 * return the DAO name to manipulate this function
281 * eg. "civicrm_api3_contact_create" or "Contact" will return "CRM_Contact_BAO_Contact"
282 * @return mixed|string
284 function _civicrm_api3_get_DAO($name) {
285 if (strpos($name, 'civicrm_api3') !== FALSE) {
286 $last = strrpos($name, '_');
287 // len ('civicrm_api3_') == 13
288 $name = substr($name, 13, $last - 13);
291 if (strtolower($name) == 'individual' ||
strtolower($name) == 'household' ||
strtolower($name) == 'organization') {
295 //hack to deal with incorrectly named BAO/DAO - see CRM-10859 -
296 // several of these have been removed but am not confident mailing_recipients is
297 // tests so have not tackled.
298 // correct approach for im is unclear
299 if($name == 'mailing_recipients' ||
$name == 'MailingRecipients'){
300 return 'CRM_Mailing_BAO_Recipients';
302 if(strtolower($name) == 'im'){
303 return 'CRM_Core_BAO_IM';
305 return CRM_Core_DAO_AllCoreTables
::getFullName(_civicrm_api_get_camel_name($name, 3));
309 * Function to return the DAO of the function or Entity
310 * @param String $name is either a function of the api (civicrm_{entity}_create or the entity name
311 * return the DAO name to manipulate this function
312 * eg. "civicrm_contact_create" or "Contact" will return "CRM_Contact_BAO_Contact"
315 function _civicrm_api3_get_BAO($name) {
316 $dao = _civicrm_api3_get_DAO($name);
320 $bao = str_replace("DAO", "BAO", $dao);
321 $file = strtr($bao, '_', '/') . '.php';
322 // Check if this entity actually has a BAO. Fall back on the DAO if not.
323 return stream_resolve_include_path($file) ?
$bao : $dao;
327 * Recursive function to explode value-separated strings into arrays
330 function _civicrm_api3_separate_values(&$values) {
331 $sp = CRM_Core_DAO
::VALUE_SEPARATOR
;
332 foreach ($values as $key => & $value) {
333 if (is_array($value)) {
334 _civicrm_api3_separate_values($value);
336 elseif (is_string($value)) {
337 if($key == 'case_type_id'){// this is to honor the way case API was originally written
338 $value = trim(str_replace($sp, ',', $value), ',');
340 elseif (strpos($value, $sp) !== FALSE) {
341 $value = explode($sp, trim($value, $sp));
348 * This is a legacy wrapper for api_store_values which will check the suitable fields using getfields
349 * rather than DAO->fields
351 * Getfields has handling for how to deal with uniquenames which dao->fields doesn't
353 * Note this is used by BAO type create functions - eg. contribution
354 * @param string $entity
355 * @param array $params
356 * @param array $values
358 function _civicrm_api3_filter_fields_for_bao($entity, &$params, &$values){
359 $fields = civicrm_api($entity,'getfields', array('version' => 3,'action' => 'create'));
360 $fields = $fields['values'];
361 _civicrm_api3_store_values($fields, $params, $values);
365 * @param array $fields
366 * @param array $params
367 * @param array $values
369 * @return Bool $valueFound
371 function _civicrm_api3_store_values(&$fields, &$params, &$values) {
374 $keys = array_intersect_key($params, $fields);
375 foreach ($keys as $name => $value) {
376 if ($name !== 'id') {
377 $values[$name] = $value;
385 * The API supports 2 types of get requestion. The more complex uses the BAO query object.
386 * This is a generic function for those functions that call it
388 * At the moment only called by contact we should extend to contribution &
389 * others that use the query object. Note that this function passes permission information in.
392 * * Ideally this would be merged with _civicrm_get_query_object but we need to resolve differences in what the
395 * @param array $params as passed into api get or getcount function
396 * @param array $additional_options array of options (so we can modify the filter)
397 * @param bool $getCount are we just after the count
401 function _civicrm_api3_get_using_query_object($entity, $params, $additional_options = array(), $getCount = NULL){
403 // Convert id to e.g. contact_id
404 if (empty($params[$entity . '_id']) && isset($params['id'])) {
405 $params[$entity . '_id'] = $params['id'];
407 unset($params['id']);
409 $options = _civicrm_api3_get_options_from_params($params, TRUE);
411 $inputParams = array_merge(
412 CRM_Utils_Array
::value('input_params', $options, array()),
413 CRM_Utils_Array
::value('input_params', $additional_options, array())
415 $returnProperties = array_merge(
416 CRM_Utils_Array
::value('return', $options, array()),
417 CRM_Utils_Array
::value('return', $additional_options, array())
419 if(empty($returnProperties)){
420 $returnProperties = NULL;
422 if(!empty($params['check_permissions'])){
423 // we will filter query object against getfields
424 $fields = civicrm_api($entity, 'getfields', array('version' => 3, 'action' => 'get'));
425 // we need to add this in as earlier in this function 'id' was unset in favour of $entity_id
426 $fields['values'][$entity . '_id'] = array();
427 $varsToFilter = array('returnProperties', 'inputParams');
428 foreach ($varsToFilter as $varToFilter){
429 if(!is_array($
$varToFilter)){
432 //I was going to throw an exception rather than silently filter out - but
433 //would need to diff out of exceptions arr other keys like 'options', 'return', 'api. etcetc
434 //so we are silently ignoring parts of their request
435 //$exceptionsArr = array_diff(array_keys($$varToFilter), array_keys($fields['values']));
436 $
$varToFilter = array_intersect_key($
$varToFilter, $fields['values']);
439 $options = array_merge($options,$additional_options);
440 $sort = CRM_Utils_Array
::value('sort', $options, NULL);
441 $offset = CRM_Utils_Array
::value('offset', $options, NULL);
442 $limit = CRM_Utils_Array
::value('limit', $options, NULL);
443 $smartGroupCache = CRM_Utils_Array
::value('smartGroupCache', $params);
447 $returnProperties = NULL;
450 $newParams = CRM_Contact_BAO_Query
::convertFormValues($inputParams);
451 foreach ($newParams as &$newParam) {
452 if($newParam[1] == '=' && is_array($newParam[2])) {
453 // we may be looking at an attempt to use the 'IN' style syntax
454 // @todo at time of writing only 'IN' & 'NOT IN' are supported for the array style syntax
455 $sqlFilter = CRM_Core_DAO
::createSqlFilter($newParam[0], $params[$newParam[0]], 'String', NULL, TRUE);
457 $newParam[1] = key($newParam[2]);
458 $newParam[2] = $sqlFilter;
463 $skipPermissions = CRM_Utils_Array
::value('check_permissions', $params)?
0 :1;
464 list($entities, $options) = CRM_Contact_BAO_Query
::apiQuery(
475 if ($getCount) { // only return the count of contacts
483 * get dao query object based on input params
484 * Ideally this would be merged with _civicrm_get_using_query_object but we need to resolve differences in what the
487 * @param array $params
488 * @param string $mode
489 * @param string $entity
490 * @return CRM_Core_DAO query object
492 function _civicrm_api3_get_query_object($params, $mode, $entity) {
493 $options = _civicrm_api3_get_options_from_params($params, TRUE, $entity, 'get');
494 $sort = CRM_Utils_Array
::value('sort', $options, NULL);
495 $offset = CRM_Utils_Array
::value('offset', $options);
496 $rowCount = CRM_Utils_Array
::value('limit', $options);
497 $inputParams = CRM_Utils_Array
::value('input_params', $options, array());
498 $returnProperties = CRM_Utils_Array
::value('return', $options, NULL);
499 if (empty($returnProperties)) {
500 $returnProperties = CRM_Contribute_BAO_Query
::defaultReturnProperties($mode);
503 $newParams = CRM_Contact_BAO_Query
::convertFormValues($inputParams);
504 $query = new CRM_Contact_BAO_Query($newParams, $returnProperties, NULL,
507 list($select, $from, $where, $having) = $query->query();
509 $sql = "$select $from $where $having";
512 $sql .= " ORDER BY $sort ";
514 if(!empty($rowCount)) {
515 $sql .= " LIMIT $offset, $rowCount ";
517 $dao = CRM_Core_DAO
::executeQuery($sql);
518 return array($dao, $query);
522 * Function transfers the filters being passed into the DAO onto the params object
524 function _civicrm_api3_dao_set_filter(&$dao, $params, $unique = TRUE, $entity) {
525 $entity = substr($dao->__table
, 8);
527 $allfields = _civicrm_api3_build_fields_array($dao, $unique);
529 $fields = array_intersect(array_keys($allfields), array_keys($params));
530 if (isset($params[$entity . "_id"])) {
531 //if entity_id is set then treat it as ID (will be overridden by id if set)
532 $dao->id
= $params[$entity . "_id"];
535 $options = _civicrm_api3_get_options_from_params($params);
536 //apply options like sort
537 _civicrm_api3_apply_options_to_dao($params, $dao, $entity);
539 //accept filters like filter.activity_date_time_high
540 // std is now 'filters' => ..
541 if (strstr(implode(',', array_keys($params)), 'filter')) {
542 if (isset($params['filters']) && is_array($params['filters'])) {
543 foreach ($params['filters'] as $paramkey => $paramvalue) {
544 _civicrm_api3_apply_filters_to_dao($paramkey, $paramvalue, $dao);
548 foreach ($params as $paramkey => $paramvalue) {
549 if (strstr($paramkey, 'filter')) {
550 _civicrm_api3_apply_filters_to_dao(substr($paramkey, 7), $paramvalue, $dao);
555 // http://issues.civicrm.org/jira/browse/CRM-9150 - stick with 'simple' operators for now
556 // support for other syntaxes is discussed in ticket but being put off for now
557 $acceptedSQLOperators = array('=', '<=', '>=', '>', '<', 'LIKE', "<>", "!=", "NOT LIKE", 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN');
562 foreach ($fields as $field) {
563 if (is_array($params[$field])) {
564 //get the actual fieldname from db
565 $fieldName = $allfields[$field]['name'];
566 $where = CRM_Core_DAO
::createSqlFilter($fieldName, $params[$field], 'String');
568 $dao->whereAdd($where);
573 $daoFieldName = $allfields[$field]['name'];
574 if (empty($daoFieldName)) {
575 throw new API_Exception("Failed to determine field name for \"$field\"");
577 $dao->{$daoFieldName} = $params[$field];
580 $dao->$field = $params[$field];
584 if (!empty($options['return']) && is_array($options['return']) && empty($options['is_count'])) {
586 $options['return']['id'] = TRUE;// ensure 'id' is included
587 $allfields = _civicrm_api3_get_unique_name_array($dao);
588 $returnMatched = array_intersect(array_keys($options['return']), $allfields);
589 foreach ($returnMatched as $returnValue) {
590 $dao->selectAdd($returnValue);
593 $unmatchedFields = array_diff(// not already matched on the field names
594 array_keys($options['return']),
598 $returnUniqueMatched = array_intersect(
600 array_flip($allfields)// but a match for the field keys
602 foreach ($returnUniqueMatched as $uniqueVal){
603 $dao->selectAdd($allfields[$uniqueVal]);
606 $dao->setApiFilter($params);
610 * Apply filters (e.g. high, low) to DAO object (prior to find)
611 * @param string $filterField field name of filter
612 * @param string $filterValue field value of filter
613 * @param object $dao DAO object
615 function _civicrm_api3_apply_filters_to_dao($filterField, $filterValue, &$dao) {
616 if (strstr($filterField, 'high')) {
617 $fieldName = substr($filterField, 0, -5);
618 $dao->whereAdd("($fieldName <= $filterValue )");
620 if (strstr($filterField, 'low')) {
621 $fieldName = substr($filterField, 0, -4);
622 $dao->whereAdd("($fieldName >= $filterValue )");
624 if($filterField == 'is_current' && $filterValue == 1){
625 $todayStart = date('Ymd000000', strtotime('now'));
626 $todayEnd = date('Ymd235959', strtotime('now'));
627 $dao->whereAdd("(start_date <= '$todayStart' OR start_date IS NULL) AND (end_date >= '$todayEnd' OR end_date IS NULL)");
628 if(property_exists($dao, 'is_active')){
629 $dao->whereAdd('is_active = 1');
635 * Get sort, limit etc options from the params - supporting old & new formats.
636 * get returnproperties for legacy
638 * @param array $params params array as passed into civicrm_api
639 * @param bool $queryObject - is this supporting a queryobject api (e.g contact) - if so we support more options
640 * for legacy report & return a unique fields array
642 * @param string $entity
643 * @param string $action
645 * @return array $options options extracted from params
647 function _civicrm_api3_get_options_from_params(&$params, $queryObject = FALSE, $entity = '', $action = '') {
649 $sort = CRM_Utils_Array
::value('sort', $params, 0);
650 $sort = CRM_Utils_Array
::value('option.sort', $params, $sort);
651 $sort = CRM_Utils_Array
::value('option_sort', $params, $sort);
653 $offset = CRM_Utils_Array
::value('offset', $params, 0);
654 $offset = CRM_Utils_Array
::value('option.offset', $params, $offset);
655 // dear PHP thought it would be a good idea to transform a.b into a_b in the get/post
656 $offset = CRM_Utils_Array
::value('option_offset', $params, $offset);
658 $limit = CRM_Utils_Array
::value('rowCount', $params, 25);
659 $limit = CRM_Utils_Array
::value('option.limit', $params, $limit);
660 $limit = CRM_Utils_Array
::value('option_limit', $params, $limit);
662 if (is_array(CRM_Utils_Array
::value('options', $params))) {
663 // is count is set by generic getcount not user
664 $is_count = CRM_Utils_Array
::value('is_count', $params['options']);
665 $offset = CRM_Utils_Array
::value('offset', $params['options'], $offset);
666 $limit = CRM_Utils_Array
::value('limit', $params['options'], $limit);
667 $sort = CRM_Utils_Array
::value('sort', $params['options'], $sort);
670 $returnProperties = array();
671 // handle the format return =sort_name,display_name...
672 if (array_key_exists('return', $params)) {
673 if (is_array($params['return'])) {
674 $returnProperties = array_fill_keys($params['return'], 1);
677 $returnProperties = explode(',', str_replace(' ', '', $params['return']));
678 $returnProperties = array_fill_keys($returnProperties, 1);
681 if ($entity && $action =='get') {
682 if (CRM_Utils_Array
::value('id',$returnProperties)) {
683 $returnProperties[$entity . '_id'] = 1;
684 unset($returnProperties['id']);
686 switch (trim(strtolower($sort))){
690 $sort = str_replace('id', $entity . '_id',$sort);
695 'offset' => CRM_Utils_Rule
::integer($offset) ?
$offset : NULL,
696 'sort' => CRM_Utils_Rule
::string($sort) ?
$sort : NULL,
697 'limit' => CRM_Utils_Rule
::integer($limit) ?
$limit : NULL,
698 'is_count' => $is_count,
699 'return' => !empty($returnProperties) ?
$returnProperties : NULL,
702 if ($options['sort'] && stristr($options['sort'], 'SELECT')) {
703 throw new API_Exception('invalid string in sort options');
709 //here comes the legacy support for $returnProperties, $inputParams e.g for contat_get
710 // if the queryobject is being used this should be used
711 $inputParams = array();
712 $legacyreturnProperties = array();
714 'sort', 'offset', 'rowCount', 'options','return',
716 foreach ($params as $n => $v) {
717 if (substr($n, 0, 7) == 'return.') {
718 $legacyreturnProperties[substr($n, 7)] = $v;
720 elseif ($n == 'id') {
721 $inputParams[$entity. '_id'] = $v;
723 elseif (in_array($n, $otherVars)) {}
725 $inputParams[$n] = $v;
726 if ($v && !is_array($v) && stristr($v, 'SELECT')) {
727 throw new API_Exception('invalid string');
731 $options['return'] = array_merge($returnProperties, $legacyreturnProperties);
732 $options['input_params'] = $inputParams;
737 * Apply options (e.g. sort, limit, order by) to DAO object (prior to find)
739 * @param array $params params array as passed into civicrm_api
740 * @param object $dao DAO object
743 function _civicrm_api3_apply_options_to_dao(&$params, &$dao, $entity) {
745 $options = _civicrm_api3_get_options_from_params($params,FALSE,$entity);
746 if(!$options['is_count']) {
747 if(!empty($options['limit'])) {
748 $dao->limit((int)$options['offset'], (int)$options['limit']);
750 if (!empty($options['sort'])) {
751 $dao->orderBy($options['sort']);
757 * build fields array. This is the array of fields as it relates to the given DAO
758 * returns unique fields as keys by default but if set but can return by DB fields
760 function _civicrm_api3_build_fields_array(&$bao, $unique = TRUE) {
761 $fields = $bao->fields();
763 if(!CRM_Utils_Array
::value('id', $fields)){
764 $entity = _civicrm_api_get_entity_name_from_dao($bao);
765 $fields['id'] = $fields[$entity . '_id'];
766 unset($fields[$entity . '_id']);
771 foreach ($fields as $field) {
772 $dbFields[$field['name']] = $field;
778 * build fields array. This is the array of fields as it relates to the given DAO
779 * returns unique fields as keys by default but if set but can return by DB fields
781 function _civicrm_api3_get_unique_name_array(&$bao) {
782 $fields = $bao->fields();
783 foreach ($fields as $field => $values) {
784 $uniqueFields[$field] = CRM_Utils_Array
::value('name',$values, $field);
786 return $uniqueFields;
790 * Converts an DAO object to an array
792 * @param object $dao (reference )object to convert
793 * @param null $params
794 * @param bool $uniqueFields
795 * @param string $entity
799 * @params array of arrays (key = id) of array of fields
804 function _civicrm_api3_dao_to_array($dao, $params = NULL, $uniqueFields = TRUE, $entity = "", $autoFind = TRUE) {
806 if(isset($params['options']) && CRM_Utils_Array
::value('is_count', $params['options'])) {
807 return $dao->count();
812 if ($autoFind && !$dao->find()) {
816 if(isset($dao->count
)) {
819 //if custom fields are required we will endeavour to set them . NB passing $entity in might be a bit clunky / unrequired
820 if (!empty($entity) && CRM_Utils_Array
::value('return', $params) && is_array($params['return'])) {
821 foreach ($params['return'] as $return) {
822 if (substr($return, 0, 6) == 'custom') {
829 $fields = array_keys(_civicrm_api3_build_fields_array($dao, $uniqueFields));
831 while ($dao->fetch()) {
833 foreach ($fields as $key) {
834 if (array_key_exists($key, $dao)) {
835 // not sure on that one
836 if ($dao->$key !== NULL) {
837 $tmp[$key] = $dao->$key;
841 $result[$dao->id
] = $tmp;
842 if (!empty($custom)) {
843 _civicrm_api3_custom_data_get($result[$dao->id
], $entity, $dao->id
);
852 * Converts an object to an array
854 * @param object $dao (reference) object to convert
855 * @param array $values (reference) array
856 * @param array|bool $uniqueFields
862 function _civicrm_api3_object_to_array(&$dao, &$values, $uniqueFields = FALSE) {
864 $fields = _civicrm_api3_build_fields_array($dao, $uniqueFields);
865 foreach ($fields as $key => $value) {
866 if (array_key_exists($key, $dao)) {
867 $values[$key] = $dao->$key;
873 * Wrapper for _civicrm_object_to_array when api supports unique fields
875 function _civicrm_api3_object_to_array_unique_fields(&$dao, &$values) {
876 return _civicrm_api3_object_to_array($dao, $values, TRUE);
881 * @param array $params
882 * @param array $values
883 * @param string $extends entity that this custom field extends (e.g. contribution, event, contact)
884 * @param string $entityId ID of entity per $extends
886 function _civicrm_api3_custom_format_params($params, &$values, $extends, $entityId = NULL) {
887 $values['custom'] = array();
888 $checkCheckBoxField = FALSE;
890 if(in_array($extends, array('Household', 'Individual', 'Organization'))) {
894 $fields = civicrm_api($entity, 'getfields', array('version' => 3, 'action' => 'create'));
895 if(!$fields['is_error']) {
896 // not sure if fields could be error - maybe change to using civicrm_api3 wrapper later - this is conservative
897 $fields = $fields['values'];
898 $checkCheckBoxField = TRUE;
901 foreach ($params as $key => $value) {
902 list($customFieldID, $customValueID) = CRM_Core_BAO_CustomField
::getKeyID($key, TRUE);
903 if ($customFieldID && (!IS_NULL($value))) {
904 if ($checkCheckBoxField && !empty($fields['custom_' . $customFieldID]) && $fields['custom_' . $customFieldID]['html_type'] == 'CheckBox') {
905 formatCheckBoxField($value, 'custom_' . $customFieldID, $entity);
907 CRM_Core_BAO_CustomField
::formatCustomField($customFieldID, $values['custom'],
908 $value, $extends, $customValueID, $entityId, FALSE, FALSE
915 * we can't rely on downstream to add separators to checkboxes so we'll check here. We should look at pushing to BAO function
916 * 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
917 * note that this is specifically tested in the GRANT api test case so later refactoring should use that as a checking point
919 * 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
920 * don't touch - lots of very cautious code in here
922 * The resulting array should look like
928 * OR one or more keys wrapped in a CRM_Core_DAO::VALUE_SEPARATOR - either it accepted by the receiving function
930 * @todo - we are probably skipping handling disabled options as presumably getoptions is not giving us them. This should be non-regressive but might
933 * @param $checkboxFieldValue
934 * @param $customFieldLabel
938 function formatCheckBoxField(&$checkboxFieldValue, $customFieldLabel, $entity) {
940 if (is_string($checkboxFieldValue) && stristr($checkboxFieldValue, CRM_Core_DAO
::VALUE_SEPARATOR
)) {
941 // we can assume it's pre-formatted
944 $options = civicrm_api($entity, 'getoptions', array('field' => $customFieldLabel, 'version' => 3));
945 if (!empty($options['is_error'])) {
946 //the check is precautionary - can probably be removed later
950 $options = $options['values'];
952 if (is_array($checkboxFieldValue)) {
953 foreach ($checkboxFieldValue as $key => $value) {
954 if (!array_key_exists($key, $options)) {
959 // we have been passed an array that is already in the 'odd' custom field format
964 // so we either have an array that is not keyed by the value or we have a string that doesn't hold separators
965 // if the array only has one item we'll treat it like any other string
966 if (is_array($checkboxFieldValue) && count($checkboxFieldValue) == 1) {
967 $possibleValue = reset($checkboxFieldValue);
969 if (is_string($checkboxFieldValue)) {
970 $possibleValue = $checkboxFieldValue;
972 if (isset($possibleValue) && array_key_exists($possibleValue, $options)) {
973 $checkboxFieldValue = CRM_Core_DAO
::VALUE_SEPARATOR
. $possibleValue . CRM_Core_DAO
::VALUE_SEPARATOR
;
976 elseif (is_array($checkboxFieldValue)) {
977 // so this time around we are considering the values in the array
978 $possibleValues = $checkboxFieldValue;
981 elseif (stristr($checkboxFieldValue, ',')) {
983 //lets see if we should separate it - we do this near the end so we
984 // ensure we have already checked that the comma is not part of a legitimate match
985 // and of course, we don't make any changes if we don't now have matches
986 $possibleValues = explode(',', $checkboxFieldValue);
989 // run out of ideas as to what the format might be - if it's a string it doesn't match with or without the ','
993 foreach ($possibleValues as $index => $possibleValue) {
994 if (array_key_exists($possibleValue, $options)) {
995 // 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)
997 elseif (array_key_exists(trim($possibleValue), $options)) {
998 $possibleValues[$index] = trim($possibleValue);
1001 $formatValue = FALSE;
1005 $checkboxFieldValue = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $possibleValues) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1011 * This function ensures that we have the right input parameters
1013 * This function is only called when $dao is passed into verify_mandatory.
1014 * The practice of passing $dao into verify_mandatory turned out to be
1015 * unsatisfactory as the required fields @ the dao level is so diffent to the abstract
1016 * api level. Hence the intention is to remove this function
1017 * & the associated param from viery_mandatory
1019 * @param array $params Associative array of property name/value
1020 * pairs to insert in new history.
1022 * @param bool $return
1024 * @daoName string DAO to check params agains
1026 * @return bool should the missing fields be returned as an array (core error created as default)
1028 * @return bool true if all fields present, depending on $result a core error is created of an array of missing fields is returned
1031 function _civicrm_api3_check_required_fields($params, $daoName, $return = FALSE) {
1032 //@deprecated - see notes
1033 if (isset($params['extends'])) {
1034 if (($params['extends'] == 'Activity' ||
1035 $params['extends'] == 'Phonecall' ||
1036 $params['extends'] == 'Meeting' ||
1037 $params['extends'] == 'Group' ||
1038 $params['extends'] == 'Contribution'
1040 ($params['style'] == 'Tab')
1042 return civicrm_api3_create_error(ts("Can not create Custom Group in Tab for " . $params['extends']));
1046 $dao = new $daoName();
1047 $fields = $dao->fields();
1050 foreach ($fields as $k => $v) {
1051 if ($v['name'] == 'id') {
1055 if (CRM_Utils_Array
::value('required', $v)) {
1056 // 0 is a valid input for numbers, CRM-8122
1057 if (!isset($params[$k]) ||
(empty($params[$k]) && !($params[$k] === 0))) {
1063 if (!empty($missing)) {
1064 if (!empty($return)) {
1068 return civicrm_api3_create_error(ts("Required fields " . implode(',', $missing) . " for $daoName are not present"));
1076 * Check permissions for a given API call.
1078 * @param $entity string API entity being accessed
1079 * @param $action string API action being performed
1080 * @param $params array params of the API call
1081 * @param $throw deprecated bool whether to throw exception instead of returning false
1084 * @return bool whether the current API user has the permission to make the call
1086 function _civicrm_api3_api_check_permission($entity, $action, &$params, $throw = TRUE) {
1087 // return early unless we’re told explicitly to do the permission check
1088 if (empty($params['check_permissions']) or $params['check_permissions'] == FALSE) {
1092 require_once 'CRM/Core/DAO/permissions.php';
1093 $permissions = _civicrm_api3_permissions($entity, $action, $params);
1095 // $params might’ve been reset by the alterAPIPermissions() hook
1096 if (isset($params['check_permissions']) and $params['check_permissions'] == FALSE) {
1100 if (!CRM_Core_Permission
::check($permissions)) {
1102 if(is_array($permissions)) {
1103 $permissions = implode(' and ', $permissions);
1105 throw new Exception("API permission check failed for $entity/$action call; insufficient permission: require $permissions");
1108 //@todo remove this - this is an internal api function called with $throw set to TRUE. It is only called with false
1109 // in tests & that should be tidied up
1118 * Function to do a 'standard' api get - when the api is only doing a $bao->find then use this
1120 * @param string $bao_name name of BAO
1121 * @param array $params params from api
1122 * @param bool $returnAsSuccess return in api success format
1123 * @param string $entity
1127 function _civicrm_api3_basic_get($bao_name, &$params, $returnAsSuccess = TRUE, $entity = "") {
1128 $bao = new $bao_name();
1129 _civicrm_api3_dao_set_filter($bao, $params, TRUE, $entity);
1130 if ($returnAsSuccess) {
1131 return civicrm_api3_create_success(_civicrm_api3_dao_to_array($bao, $params, FALSE, $entity), $params, $entity, 'get');
1134 return _civicrm_api3_dao_to_array($bao, $params, FALSE, $entity);
1139 * Function to do a 'standard' api create - when the api is only doing a $bao::create then use this
1140 * @param string $bao_name Name of BAO Class
1141 * @param array $params parameters passed into the api call
1142 * @param string $entity Entity - pass in if entity is non-standard & required $ids array
1145 function _civicrm_api3_basic_create($bao_name, &$params, $entity = NULL) {
1147 $args = array(&$params);
1148 if (!empty($entity)) {
1149 $ids = array($entity => CRM_Utils_Array
::value('id', $params));
1153 if (method_exists($bao_name, 'create')) {
1155 $fct_name = $bao_name . '::' . $fct;
1156 $bao = call_user_func_array(array($bao_name, $fct), $args);
1158 elseif (method_exists($bao_name, 'add')) {
1160 $fct_name = $bao_name . '::' . $fct;
1161 $bao = call_user_func_array(array($bao_name, $fct), $args);
1164 $fct_name = '_civicrm_api3_basic_create_fallback';
1165 $bao = _civicrm_api3_basic_create_fallback($bao_name, $params);
1168 if (is_null($bao)) {
1169 return civicrm_api3_create_error('Entity not created (' . $fct_name . ')');
1171 elseif (is_a($bao, 'CRM_Core_Error')) {
1172 //some wierd circular thing means the error takes itself as an argument
1173 $msg = $bao->getMessages($bao);
1174 // the api deals with entities on a one-by-one basis. However, the contribution bao pushes entities
1175 // onto the error object - presumably because the contribution import is not handling multiple errors correctly
1176 // so we need to reset the error object here to avoid getting concatenated errors
1177 //@todo - the mulitple error handling should be moved out of the contribution object to the import / multiple entity processes
1178 CRM_Core_Error
::singleton()->reset();
1179 throw new API_Exception($msg);
1183 _civicrm_api3_object_to_array($bao, $values[$bao->id
]);
1184 return civicrm_api3_create_success($values, $params, $entity, 'create', $bao);
1189 * For BAO's which don't have a create() or add() functions, use this fallback implementation.
1191 * @fixme There's an intuitive sense that this behavior should be defined somehow in the BAO/DAO class
1192 * structure. In practice, that requires a fair amount of refactoring and/or kludgery.
1194 * @param string $bao_name
1195 * @param array $params
1197 * @throws API_Exception
1198 * @return CRM_Core_DAO|NULL an instance of the BAO
1200 function _civicrm_api3_basic_create_fallback($bao_name, &$params) {
1201 $entityName = CRM_Core_DAO_AllCoreTables
::getBriefName(get_parent_class($bao_name));
1202 if (empty($entityName)) {
1203 throw new API_Exception("Class \"$bao_name\" does not map to an entity name", "unmapped_class_to_entity", array(
1204 'class_name' => $bao_name,
1207 $hook = empty($params['id']) ?
'create' : 'edit';
1209 CRM_Utils_Hook
::pre($hook, $entityName, CRM_Utils_Array
::value('id', $params), $params);
1210 $instance = new $bao_name();
1211 $instance->copyValues($params);
1213 CRM_Utils_Hook
::post($hook, $entityName, $instance->id
, $instance);
1219 * Function to do a 'standard' api del - when the api is only doing a $bao::del then use this
1220 * if api::del doesn't exist it will try DAO delete method
1222 function _civicrm_api3_basic_delete($bao_name, &$params) {
1224 civicrm_api3_verify_mandatory($params, NULL, array('id'));
1225 $args = array(&$params['id']);
1226 if (method_exists($bao_name, 'del')) {
1227 $bao = call_user_func_array(array($bao_name, 'del'), $args);
1228 if ($bao !== FALSE) {
1229 return civicrm_api3_create_success(TRUE);
1231 throw new API_Exception('Could not delete entity id ' . $params['id']);
1233 elseif (method_exists($bao_name, 'delete')) {
1234 $dao = new $bao_name();
1235 $dao->id
= $params['id'];
1237 while ($dao->fetch()) {
1239 return civicrm_api3_create_success();
1243 throw new API_Exception('Could not delete entity id ' . $params['id']);
1247 throw new API_Exception('no delete method found');
1251 * Get custom data for the given entity & Add it to the returnArray as 'custom_123' = 'custom string' AND 'custom_123_1' = 'custom string'
1252 * Where 123 is field value & 1 is the id within the custom group data table (value ID)
1254 * @param array $returnArray - array to append custom data too - generally $result[4] where 4 is the entity id.
1255 * @param string $entity e.g membership, event
1257 * @param int $groupID - per CRM_Core_BAO_CustomGroup::getTree
1258 * @param int $subType e.g. membership_type_id where custom data doesn't apply to all membership types
1259 * @param string $subName - Subtype of entity
1261 function _civicrm_api3_custom_data_get(&$returnArray, $entity, $entity_id, $groupID = NULL, $subType = NULL, $subName = NULL) {
1262 $groupTree = &CRM_Core_BAO_CustomGroup
::getTree($entity,
1263 CRM_Core_DAO
::$_nullObject,
1269 $groupTree = CRM_Core_BAO_CustomGroup
::formatGroupTree($groupTree, 1, CRM_Core_DAO
::$_nullObject);
1270 $customValues = array();
1271 CRM_Core_BAO_CustomGroup
::setDefaults($groupTree, $customValues);
1272 if (!empty($customValues)) {
1273 foreach ($customValues as $key => $val) {
1274 if (strstr($key, '_id')) {
1275 $idkey = substr($key, 0, -3);
1276 $returnArray['custom_' . (CRM_Core_BAO_CustomField
::getKeyID($idkey) . "_id")] = $val;
1277 $returnArray[$key] = $val;
1280 // per standard - return custom_fieldID
1281 $returnArray['custom_' . (CRM_Core_BAO_CustomField
::getKeyID($key))] = $val;
1283 //not standard - but some api did this so guess we should keep - cheap as chips
1284 $returnArray[$key] = $val;
1291 * Validate fields being passed into API. This function relies on the getFields function working accurately
1292 * for the given API. If error mode is set to TRUE then it will also check
1295 * As of writing only date was implemented.
1296 * @param string $entity
1297 * @param string $action
1298 * @param array $params -
1299 * @param array $fields response from getfields all variables are the same as per civicrm_api
1300 * @param bool $errorMode errorMode do intensive post fail checks?
1303 function _civicrm_api3_validate_fields($entity, $action, &$params, $fields, $errorMode = False) {
1304 $fields = array_intersect_key($fields, $params);
1305 foreach ($fields as $fieldName => $fieldInfo) {
1306 switch (CRM_Utils_Array
::value('type', $fieldInfo)) {
1307 case CRM_Utils_Type
::T_INT
:
1308 //field is of type integer
1309 _civicrm_api3_validate_integer($params, $fieldName, $fieldInfo, $entity);
1314 //field is of type date or datetime
1315 _civicrm_api3_validate_date($params, $fieldName, $fieldInfo);
1319 _civicrm_api3_validate_html($params, $fieldName, $fieldInfo);
1322 case CRM_Utils_Type
::T_STRING
:
1323 _civicrm_api3_validate_string($params, $fieldName, $fieldInfo, $entity);
1326 case CRM_Utils_Type
::T_MONEY
:
1327 if (!CRM_Utils_Rule
::money($params[$fieldName]) && !empty($params[$fieldName])) {
1328 throw new Exception($fieldName . " is not a valid amount: " . $params[$fieldName]);
1332 // intensive checks - usually only called after DB level fail
1333 if (!empty($errorMode) && strtolower($action) == 'create') {
1334 if (CRM_Utils_Array
::value('FKClassName', $fieldInfo)) {
1335 if (CRM_Utils_Array
::value($fieldName, $params)) {
1336 _civicrm_api3_validate_constraint($params, $fieldName, $fieldInfo);
1338 elseif (CRM_Utils_Array
::value('required', $fieldInfo)) {
1339 throw new Exception("DB Constraint Violation - possibly $fieldName should possibly be marked as mandatory for this API. If so, please raise a bug report");
1342 if (CRM_Utils_Array
::value('api.unique', $fieldInfo)) {
1343 $params['entity'] = $entity;
1344 _civicrm_api3_validate_uniquekey($params, $fieldName, $fieldInfo);
1351 * Validate date fields being passed into API.
1352 * It currently converts both unique fields and DB field names to a mysql date.
1353 * @todo - probably the unique field handling & the if exists handling is now done before this
1354 * function is reached in the wrapper - can reduce this code down to assume we
1355 * are only checking the passed in field
1357 * It also checks against the RULE:date function. This is a centralisation of code that was scattered and
1358 * may not be the best thing to do. There is no code level documentation on the existing functions to work off
1360 * @param array $params params from civicrm_api
1361 * @param string $fieldName uniquename of field being checked
1362 * @param array $fieldInfo array of fields from getfields function
1365 function _civicrm_api3_validate_date(&$params, &$fieldName, &$fieldInfo) {
1366 //should we check first to prevent it from being copied if they have passed in sql friendly format?
1367 if (CRM_Utils_Array
::value($fieldInfo['name'], $params)) {
1368 //accept 'whatever strtotime accepts
1369 if (strtotime($params[$fieldInfo['name']]) === FALSE) {
1370 throw new Exception($fieldInfo['name'] . " is not a valid date: " . $params[$fieldInfo['name']]);
1372 $format = ($fieldInfo['type'] == CRM_Utils_Type
::T_DATE
) ?
'Ymd000000' : 'YmdHis';
1373 $params[$fieldInfo['name']] = CRM_Utils_Date
::processDate($params[$fieldInfo['name']], NULL, FALSE, $format);
1375 if ((CRM_Utils_Array
::value('name', $fieldInfo) != $fieldName) && CRM_Utils_Array
::value($fieldName, $params)) {
1376 //If the unique field name differs from the db name & is set handle it here
1377 if (strtotime($params[$fieldName]) === FALSE) {
1378 throw new Exception($fieldName . " is not a valid date: " . $params[$fieldName]);
1380 $params[$fieldName] = CRM_Utils_Date
::processDate($params[$fieldName]);
1385 * Validate foreign constraint fields being passed into API.
1387 * @param array $params params from civicrm_api
1388 * @param string $fieldName uniquename of field being checked
1389 * @param array $fieldInfo array of fields from getfields function
1392 function _civicrm_api3_validate_constraint(&$params, &$fieldName, &$fieldInfo) {
1393 $dao = new $fieldInfo['FKClassName'];
1394 $dao->id
= $params[$fieldName];
1396 $dao->selectAdd('id');
1397 if (!$dao->find()) {
1398 throw new Exception("$fieldName is not valid : " . $params[$fieldName]);
1403 * Validate foreign constraint fields being passed into API.
1405 * @param array $params params from civicrm_api
1406 * @param string $fieldName uniquename of field being checked
1407 * @param $fieldInfo array of fields from getfields function
1410 function _civicrm_api3_validate_uniquekey(&$params, &$fieldName, &$fieldInfo) {
1411 $existing = civicrm_api($params['entity'], 'get', array(
1412 'version' => $params['version'],
1413 $fieldName => $params[$fieldName],
1415 // an entry already exists for this unique field
1416 if ($existing['count'] == 1) {
1417 // question - could this ever be a security issue?
1418 throw new Exception("Field: `$fieldName` must be unique. An conflicting entity already exists - id: " . $existing['id']);
1423 * Generic implementation of the "replace" action.
1425 * Replace the old set of entities (matching some given keys) with a new set of
1426 * entities (matching the same keys).
1428 * Note: This will verify that 'values' is present, but it does not directly verify
1429 * any other parameters.
1431 * @param string $entity entity name
1432 * @param array $params params from civicrm_api, including:
1433 * - 'values': an array of records to save
1434 * - all other items: keys which identify new/pre-existing records
1437 function _civicrm_api3_generic_replace($entity, $params) {
1439 $transaction = new CRM_Core_Transaction();
1441 if (!is_array($params['values'])) {
1442 throw new Exception("Mandatory key(s) missing from params array: values");
1445 // Extract the keys -- somewhat scary, don't think too hard about it
1446 $baseParams = _civicrm_api3_generic_replace_base_params($params);
1448 // Lookup pre-existing records
1449 $preexisting = civicrm_api($entity, 'get', $baseParams, $params);
1450 if (civicrm_error($preexisting)) {
1451 $transaction->rollback();
1452 return $preexisting;
1455 // Save the new/updated records
1457 foreach ($params['values'] as $replacement) {
1458 // Sugar: Don't force clients to duplicate the 'key' data
1459 $replacement = array_merge($baseParams, $replacement);
1460 $action = (isset($replacement['id']) ||
isset($replacement[$entity . '_id'])) ?
'update' : 'create';
1461 $create = civicrm_api($entity, $action, $replacement);
1462 if (civicrm_error($create)) {
1463 $transaction->rollback();
1466 foreach ($create['values'] as $entity_id => $entity_value) {
1467 $creates[$entity_id] = $entity_value;
1471 // Remove stale records
1472 $staleIDs = array_diff(
1473 array_keys($preexisting['values']),
1474 array_keys($creates)
1476 foreach ($staleIDs as $staleID) {
1477 $delete = civicrm_api($entity, 'delete', array(
1478 'version' => $params['version'],
1481 if (civicrm_error($delete)) {
1482 $transaction->rollback();
1487 return civicrm_api3_create_success($creates, $params);
1489 catch(PEAR_Exception
$e) {
1490 $transaction->rollback();
1491 return civicrm_api3_create_error($e->getMessage());
1493 catch(Exception
$e) {
1494 $transaction->rollback();
1495 return civicrm_api3_create_error($e->getMessage());
1504 function _civicrm_api3_generic_replace_base_params($params) {
1505 $baseParams = $params;
1506 unset($baseParams['values']);
1507 unset($baseParams['sequential']);
1508 unset($baseParams['options']);
1513 * returns fields allowable by api
1515 * @param $entity string Entity to query
1516 * @param bool $unique index by unique fields?
1517 * @param array $params
1521 function _civicrm_api_get_fields($entity, $unique = FALSE, &$params = array(
1523 $unsetIfEmpty = array('dataPattern', 'headerPattern', 'default', 'export', 'import');
1524 $dao = _civicrm_api3_get_DAO($entity);
1529 $fields = $d->fields();
1530 // replace uniqueNames by the normal names as the key
1531 if (empty($unique)) {
1532 foreach ($fields as $name => & $field) {
1533 //getting rid of unused attributes
1534 foreach ($unsetIfEmpty as $attr) {
1535 if (empty($field[$attr])) {
1536 unset($field[$attr]);
1539 if ($name == $field['name']) {
1542 if (array_key_exists($field['name'], $fields)) {
1543 $field['error'] = 'name conflict';
1544 // it should never happen, but better safe than sorry
1547 $fields[$field['name']] = $field;
1548 $fields[$field['name']]['uniqueName'] = $name;
1549 unset($fields[$name]);
1552 $fields +
= _civicrm_api_get_custom_fields($entity, $params);
1557 * Return an array of fields for a given entity - this is the same as the BAO function but
1558 * fields are prefixed with 'custom_' to represent api params
1560 function _civicrm_api_get_custom_fields($entity, &$params) {
1561 $customfields = array();
1562 $entity = _civicrm_api_get_camel_name($entity);
1563 if (strtolower($entity) == 'contact') {
1564 // Use sub-type if available, otherwise stick with 'Contact'
1565 $entity = CRM_Utils_Array
::value('contact_type', $params);
1567 $retrieveOnlyParent = FALSE;
1568 // we could / should probably test for other subtypes here - e.g. activity_type_id
1569 if($entity == 'Contact'){
1570 empty($params['contact_sub_type']);
1572 $customfields = CRM_Core_BAO_CustomField
::getFields($entity,
1575 CRM_Utils_Array
::value('contact_sub_type', $params, FALSE),
1577 $retrieveOnlyParent,
1581 // find out if we have any requests to resolve options
1582 $getoptions = CRM_Utils_Array
::value('get_options', CRM_Utils_Array
::value('options',$params));
1583 if(!is_array($getoptions)){
1584 $getoptions = array($getoptions);
1587 foreach ($customfields as $key => $value) {
1588 // Regular fields have a 'name' property
1589 $value['name'] = 'custom_' . $key;
1590 $value['type'] = _getStandardTypeFromCustomDataType($value['data_type']);
1591 $customfields['custom_' . $key] = $value;
1592 if (in_array('custom_' . $key, $getoptions)) {
1593 $customfields['custom_' . $key]['options'] = CRM_Core_BAO_CustomOption
::valuesByID($key);
1595 unset($customfields[$key]);
1597 return $customfields;
1600 * Translate the custom field data_type attribute into a std 'type'
1602 function _getStandardTypeFromCustomDataType($dataType) {
1604 'String' => CRM_Utils_Type
::T_STRING
,
1605 'Int' => CRM_Utils_Type
::T_INT
,
1606 'Money' => CRM_Utils_Type
::T_MONEY
,
1607 'Memo' => CRM_Utils_Type
::T_LONGTEXT
,
1608 'Float' => CRM_Utils_Type
::T_FLOAT
,
1609 'Date' => CRM_Utils_Type
::T_DATE
,
1610 'Boolean' => CRM_Utils_Type
::T_BOOLEAN
,
1611 'StateProvince' => CRM_Utils_Type
::T_INT
,
1612 'File' => CRM_Utils_Type
::T_STRING
,
1613 'Link' => CRM_Utils_Type
::T_STRING
,
1614 'ContactReference' => CRM_Utils_Type
::T_INT
,
1615 'Country' => CRM_Utils_Type
::T_INT
,
1617 return $mapping[$dataType];
1620 * Return array of defaults for the given API (function is a wrapper on getfields)
1622 function _civicrm_api3_getdefaults($apiRequest, $fields) {
1623 $defaults = array();
1625 foreach ($fields as $field => $values) {
1626 if (isset($values['api.default'])) {
1627 $defaults[$field] = $values['api.default'];
1634 * Return array of defaults for the given API (function is a wrapper on getfields)
1636 function _civicrm_api3_getrequired($apiRequest, $fields) {
1637 $required = array('version');
1639 foreach ($fields as $field => $values) {
1640 if (CRM_Utils_Array
::value('api.required', $values)) {
1641 $required[] = $field;
1648 * Fill params array with alternate (alias) values where a field has an alias and that is filled & the main field isn't
1649 * If multiple aliases the last takes precedence
1651 * Function also swaps unique fields for non-unique fields & vice versa.
1653 function _civicrm_api3_swap_out_aliases(&$apiRequest, $fields) {
1654 foreach ($fields as $field => $values) {
1655 $uniqueName = CRM_Utils_Array
::value('uniqueName', $values);
1656 if (CRM_Utils_Array
::value('api.aliases', $values)) {
1657 // if aliased field is not set we try to use field alias
1658 if (!isset($apiRequest['params'][$field])) {
1659 foreach ($values['api.aliases'] as $alias) {
1660 if (isset($apiRequest['params'][$alias])) {
1661 $apiRequest['params'][$field] = $apiRequest['params'][$alias];
1663 //unset original field nb - need to be careful with this as it may bring inconsistencies
1664 // out of the woodwork but will be implementing only as _spec function extended
1665 unset($apiRequest['params'][$alias]);
1669 if (!isset($apiRequest['params'][$field])
1670 && CRM_Utils_Array
::value('name', $values)
1671 && $field != $values['name']
1672 && isset($apiRequest['params'][$values['name']])
1674 $apiRequest['params'][$field] = $apiRequest['params'][$values['name']];
1675 // note that it would make sense to unset the original field here but tests need to be in place first
1677 if (!isset($apiRequest['params'][$field])
1679 && $field != $uniqueName
1680 && array_key_exists($uniqueName, $apiRequest['params'])
1683 $apiRequest['params'][$field] = CRM_Utils_Array
::value($values['uniqueName'], $apiRequest['params']);
1684 // note that it would make sense to unset the original field here but tests need to be in place first
1691 * Validate integer fields being passed into API.
1692 * It currently converts the incoming value 'user_contact_id' into the id of the currenty logged in user
1694 * @param array $params params from civicrm_api
1695 * @param string $fieldName uniquename of field being checked
1696 * @param array $fieldInfo array of fields from getfields function
1697 * @param string $entity
1698 * @throws API_Exception
1700 function _civicrm_api3_validate_integer(&$params, &$fieldName, &$fieldInfo, $entity) {
1701 //if fieldname exists in params
1702 if (CRM_Utils_Array
::value($fieldName, $params)) {
1703 // if value = 'user_contact_id' (or similar), replace value with contact id
1704 if (!is_numeric($params[$fieldName]) && is_scalar($params[$fieldName])) {
1705 $realContactId = _civicrm_api3_resolve_contactID($params[$fieldName]);
1706 if ('unknown-user' === $realContactId) {
1707 throw new API_Exception("\"$fieldName\" \"{$params[$fieldName]}\" cannot be resolved to a contact ID", 2002, array('error_field' => $fieldName,"type"=>"integer"));
1708 } elseif (is_numeric($realContactId)) {
1709 $params[$fieldName] = $realContactId;
1712 if (!empty($fieldInfo['pseudoconstant']) ||
!empty($fieldInfo['options'])) {
1713 _civicrm_api3_api_match_pseudoconstant($params, $entity, $fieldName, $fieldInfo);
1716 // After swapping options, ensure we have an integer(s)
1717 foreach ((array) ($params[$fieldName]) as $value) {
1718 if ($value && !is_numeric($value) && $value !== 'null' && !is_array($value)) {
1719 throw new API_Exception("$fieldName is not a valid integer", 2001, array('error_field' => $fieldName, "type" => "integer"));
1723 // Check our field length
1724 if(is_string($params[$fieldName]) &&
1725 CRM_Utils_Array
::value('maxlength',$fieldInfo)
1726 && strlen($params[$fieldName]) > $fieldInfo['maxlength']
1728 throw new API_Exception( $params[$fieldName] . " is " . strlen($params[$fieldName]) . " characters - longer than $fieldName length" . $fieldInfo['maxlength'] . ' characters',
1729 2100, array('field' => $fieldName, "max_length"=>$fieldInfo['maxlength'])
1736 * Determine a contact ID using a string expression
1738 * @param string $contactIdExpr e.g. "user_contact_id" or "@user:username"
1739 * @return int|NULL|'unknown-user'
1741 function _civicrm_api3_resolve_contactID($contactIdExpr) {
1742 //if value = 'user_contact_id' replace value with logged in user id
1743 if ($contactIdExpr == "user_contact_id") {
1744 return CRM_Core_Session
::getLoggedInContactID();
1746 elseif (preg_match('/^@user:(.*)$/', $contactIdExpr, $matches)) {
1747 $config = CRM_Core_Config
::singleton();
1749 $ufID = $config->userSystem
->getUfId($matches[1]);
1751 return 'unknown-user';
1754 $contactID = CRM_Core_BAO_UFMatch
::getContactId($ufID);
1756 return 'unknown-user';
1765 * Validate html (check for scripting attack)
1766 * @param array $params
1767 * @param string $fieldName
1768 * @param array $fieldInfo
1770 * @throws API_Exception
1772 function _civicrm_api3_validate_html(&$params, &$fieldName, $fieldInfo) {
1773 if ($value = CRM_Utils_Array
::value($fieldName, $params)) {
1774 if (!CRM_Utils_Rule
::xssString($value)) {
1775 throw new API_Exception('Illegal characters in input (potential scripting attack)', array("field"=>$fieldName,"error_code"=>"xss"));
1781 * Validate string fields being passed into API.
1782 * @param array $params params from civicrm_api
1783 * @param string $fieldName uniquename of field being checked
1784 * @param array $fieldInfo array of fields from getfields function
1785 * @param string $entity
1786 * @throws API_Exception
1789 function _civicrm_api3_validate_string(&$params, &$fieldName, &$fieldInfo, $entity) {
1790 // If fieldname exists in params
1791 $value = CRM_Utils_Array
::value($fieldName, $params, '');
1792 if(!is_array($value)){
1793 $value = (string) $value;
1796 //@todo what do we do about passed in arrays. For many of these fields
1797 // the missing piece of functionality is separating them to a separated string
1798 // & many save incorrectly. But can we change them wholesale?
1801 if (!CRM_Utils_Rule
::xssString($value)) {
1802 throw new Exception('Illegal characters in input (potential scripting attack)');
1804 if ($fieldName == 'currency') {
1805 if (!CRM_Utils_Rule
::currencyCode($value)) {
1806 throw new Exception("Currency not a valid code: $value");
1809 if (!empty($fieldInfo['pseudoconstant']) ||
!empty($fieldInfo['options']) ||
!empty($fieldInfo['enumValues'])) {
1810 _civicrm_api3_api_match_pseudoconstant($params, $entity, $fieldName, $fieldInfo);
1812 // Check our field length
1813 elseif (is_string($value) && !empty($fieldInfo['maxlength']) && strlen(utf8_decode($value)) > $fieldInfo['maxlength']) {
1814 throw new API_Exception("Value for $fieldName is " . strlen(utf8_decode($value)) . " characters - This field has a maxlength of {$fieldInfo['maxlength']} characters.",
1815 2100, array('field' => $fieldName)
1822 * Validate & swap out any pseudoconstants / options
1824 * @param array $params: api parameters
1825 * @param string $entity: api entity name
1826 * @param string $fieldName: field name used in api call (not necessarily the canonical name)
1827 * @param array $fieldInfo: getfields meta-data
1829 function _civicrm_api3_api_match_pseudoconstant(&$params, $entity, $fieldName, $fieldInfo) {
1830 $options = CRM_Utils_Array
::value('options', $fieldInfo);
1832 if(strtolower($entity) == 'profile' && !empty($fieldInfo['entity'])) {
1833 // we need to get the options from the entity the field relates to
1834 $entity = $fieldInfo['entity'];
1836 $options = civicrm_api($entity, 'getoptions', array('version' => 3, 'field' => $fieldInfo['name'], 'context' => 'validate'));
1837 $options = CRM_Utils_Array
::value('values', $options, array());
1840 // If passed a value-separated string, explode to an array, then re-implode after matching values
1842 if (is_string($params[$fieldName]) && strpos($params[$fieldName], CRM_Core_DAO
::VALUE_SEPARATOR
) !== FALSE) {
1843 $params[$fieldName] = CRM_Utils_Array
::explodePadded($params[$fieldName]);
1846 // If passed multiple options, validate each
1847 if (is_array($params[$fieldName])) {
1848 foreach ($params[$fieldName] as &$value) {
1849 if (!is_array($value)) {
1850 _civicrm_api3_api_match_pseudoconstant_value($value, $options, $fieldName);
1853 // TODO: unwrap the call to implodePadded from the conditional and do it always
1854 // need to verify that this is safe and doesn't break anything though.
1855 // Better yet would be to leave it as an array and ensure that every dao/bao can handle array input
1857 CRM_Utils_Array
::implodePadded($params[$fieldName]);
1861 _civicrm_api3_api_match_pseudoconstant_value($params[$fieldName], $options, $fieldName);
1866 * Validate & swap a single option value for a field
1868 * @param string $value: field value
1869 * @param array $options: array of options for this field
1870 * @param string $fieldName: field name used in api call (not necessarily the canonical name)
1871 * @throws API_Exception
1873 function _civicrm_api3_api_match_pseudoconstant_value(&$value, $options, $fieldName) {
1874 // If option is a key, no need to translate
1875 if (array_key_exists($value, $options)) {
1879 // Translate value into key
1880 $newValue = array_search($value, $options);
1881 if ($newValue !== FALSE) {
1885 // Case-insensitive matching
1886 $newValue = strtolower($value);
1887 $options = array_map("strtolower", $options);
1888 $newValue = array_search($newValue, $options);
1889 if ($newValue === FALSE) {
1890 throw new API_Exception("'$value' is not a valid option for field $fieldName", 2001, array('error_field' => $fieldName));
1896 * Returns the canonical name of a field
1897 * @param $entity: api entity name (string should already be standardized - no camelCase)
1898 * @param $fieldName: any variation of a field's name (name, unique_name, api.alias)
1900 * @return (string|bool) fieldName or FALSE if the field does not exist
1902 function _civicrm_api3_api_resolve_alias($entity, $fieldName) {
1903 if (strpos($fieldName, 'custom_') === 0 && is_numeric($fieldName[7])) {
1906 if ($fieldName == "{$entity}_id") {
1909 $result = civicrm_api($entity, 'getfields', array(
1911 'action' => 'create',
1913 $meta = $result['values'];
1914 if (!isset($meta[$fieldName]['name']) && isset($meta[$fieldName . '_id'])) {
1915 $fieldName = $fieldName . '_id';
1917 if (isset($meta[$fieldName])) {
1918 return $meta[$fieldName]['name'];
1920 foreach ($meta as $info) {
1921 if ($fieldName == CRM_Utils_Array
::value('uniqueName', $info)) {
1922 return $info['name'];
1924 if (array_search($fieldName, CRM_Utils_Array
::value('api.aliases', $info, array())) !== FALSE) {
1925 return $info['name'];