ad2f2e4f90b7821ece2288b58195381922af9b94
[civicrm-core.git] / api / v3 / utils.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.4 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
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 * File for CiviCRM APIv3 utilitity functions
30 *
31 * @package CiviCRM_APIv3
32 * @subpackage API_utils
33 *
34 * @copyright CiviCRM LLC (c) 2004-2013
35 * @version $Id: utils.php 30879 2010-11-22 15:45:55Z shot $
36 *
37 */
38
39 /**
40 * Initialize CiviCRM - should be run at the start of each API function
41 */
42 function _civicrm_api3_initialize() {
43 require_once 'CRM/Core/ClassLoader.php';
44 CRM_Core_ClassLoader::singleton()->register();
45 CRM_Core_Config::singleton();
46 }
47
48 /**
49 * Wrapper Function for civicrm_verify_mandatory to make it simple to pass either / or fields for checking
50 *
51 * @param array $params array of fields to check
52 * @param array $daoName string DAO to check for required fields (create functions only)
53 * @param array $keyoptions
54 *
55 * @internal param array $keys list of required fields options. One of the options is required
56 * @return null or throws error if there the required fields not present
57 * @
58 */
59 function civicrm_api3_verify_one_mandatory($params, $daoName = NULL, $keyoptions = array(
60 )) {
61 $keys = array(array());
62 foreach ($keyoptions as $key) {
63 $keys[0][] = $key;
64 }
65 civicrm_api3_verify_mandatory($params, $daoName, $keys);
66 }
67
68 /**
69 * Function to check mandatory fields are included
70 *
71 * @param array $params array of fields to check
72 * @param array $daoName string DAO to check for required fields (create functions only)
73 * @param array $keys list of required fields. A value can be an array denoting that either this or that is required.
74 * @param bool $verifyDAO
75 *
76 * @throws API_Exception
77 * @return null or throws error if there the required fields not present
78 *
79 * @todo see notes on _civicrm_api3_check_required_fields regarding removing $daoName param
80 */
81 function civicrm_api3_verify_mandatory($params, $daoName = NULL, $keys = array(
82 ), $verifyDAO = TRUE) {
83
84 $unmatched = array();
85 if ($daoName != NULL && $verifyDAO && empty($params['id'])) {
86 $unmatched = _civicrm_api3_check_required_fields($params, $daoName, TRUE);
87 if (!is_array($unmatched)) {
88 $unmatched = array();
89 }
90 }
91
92 if (!empty($params['id'])) {
93 $keys = array('version');
94 }
95 else {
96 if (!in_array('version', $keys)) {
97 // required from v3 onwards
98 $keys[] = 'version';
99 }
100 }
101 foreach ($keys as $key) {
102 if (is_array($key)) {
103 $match = 0;
104 $optionset = array();
105 foreach ($key as $subkey) {
106 if (!array_key_exists($subkey, $params) || empty($params[$subkey])) {
107 $optionset[] = $subkey;
108 }
109 else {
110 // as long as there is one match then we don't need to rtn anything
111 $match = 1;
112 }
113 }
114 if (empty($match) && !empty($optionset)) {
115 $unmatched[] = "one of (" . implode(", ", $optionset) . ")";
116 }
117 }
118 else {
119 // Disallow empty values except for the number zero.
120 // TODO: create a utility for this since it's needed in many places
121 if (!array_key_exists($key, $params) || (empty($params[$key]) && $params[$key] !== 0 && $params[$key] !== '0')) {
122 $unmatched[] = $key;
123 }
124 }
125 }
126 if (!empty($unmatched)) {
127 throw new API_Exception("Mandatory key(s) missing from params array: " . implode(", ", $unmatched),"mandatory_missing",array("fields"=>$unmatched));
128 }
129 }
130
131 /**
132 *
133 * @param <type> $data
134 * @param array $data
135 * @param object $dao DAO / BAO object to be freed here
136 *
137 * @throws API_Exception
138 * @return array <type>
139 */
140 function civicrm_api3_create_error($msg, $data = array(), &$dao = NULL) {
141 //fix me - $dao should be param 4 & 3 should be $apiRequest
142 if (is_object($dao)) {
143 $dao->free();
144 }
145
146 if (is_array($dao)) {
147 if ($msg == 'DB Error: constraint violation' || substr($msg, 0,9) == 'DB Error:' || $msg == 'DB Error: already exists') {
148 try {
149 $fields = _civicrm_api3_api_getfields($dao);
150 _civicrm_api3_validate_fields($dao['entity'], $dao['action'], $dao['params'], $fields, TRUE);
151 }
152 catch(Exception $e) {
153 $msg = $e->getMessage();
154 }
155 }
156 }
157 $data['is_error'] = 1;
158 $data['error_message'] = $msg;
159 // we will show sql to privelledged user only (not sure of a specific
160 // security hole here but seems sensible - perhaps should apply to the trace as well?
161 if(isset($data['sql']) && CRM_Core_Permission::check('Administer CiviCRM')) {
162 $data['debug_information'] = $data['sql'];
163 }
164 if (is_array($dao) && isset($dao['params']) && is_array($dao['params']) && CRM_Utils_Array::value('api.has_parent', $dao['params'])) {
165 $errorCode = empty($data['error_code']) ? 'chained_api_failed' : $data['error_code'];
166 throw new API_Exception('Error in call to ' . $dao['entity'] . '_' . $dao['action'] . ' : ' . $msg, $errorCode, $data);
167 }
168 return $data;
169 }
170
171 /**
172 * Format array in result output styple
173 *
174 * @param array $values values generated by API operation (the result)
175 * @param array $params parameters passed into API call
176 * @param string $entity the entity being acted on
177 * @param string $action the action passed to the API
178 * @param object $dao DAO object to be freed here
179 * @param array $extraReturnValues additional values to be added to top level of result array(
180 * - this param is currently used for legacy behaviour support
181 *
182 * @return array $result
183 */
184 function civicrm_api3_create_success($values = 1, $params = array(
185 ), $entity = NULL, $action = NULL, &$dao = NULL, $extraReturnValues = array()) {
186 $result = array();
187 $result['is_error'] = 0;
188 //lets set the ['id'] field if it's not set & we know what the entity is
189 if (is_array($values) && !empty($entity)) {
190 foreach ($values as $key => $item) {
191 if (empty($item['id']) && !empty($item[$entity . "_id"])) {
192 $values[$key]['id'] = $item[$entity . "_id"];
193 }
194 if(!empty($item['financial_type_id'])){
195 //4.3 legacy handling
196 $values[$key]['contribution_type_id'] = $item['financial_type_id'];
197 }
198 if(!empty($item['next_sched_contribution_date'])){
199 // 4.4 legacy handling
200 $values[$key]['next_sched_contribution'] = $item['next_sched_contribution_date'];
201 }
202 }
203 }
204
205 if (is_array($params) && !empty($params['debug'])) {
206 if (is_string($action) && $action != 'getfields') {
207 $apiFields = civicrm_api($entity, 'getfields', array('version' => 3, 'action' => $action) + $params);
208 }
209 elseif ($action != 'getfields') {
210 $apiFields = civicrm_api($entity, 'getfields', array('version' => 3) + $params);
211 }
212 else {
213 $apiFields = FALSE;
214 }
215
216 $allFields = array();
217 if ($action != 'getfields' && is_array($apiFields) && is_array(CRM_Utils_Array::value('values', $apiFields))) {
218 $allFields = array_keys($apiFields['values']);
219 }
220 $paramFields = array_keys($params);
221 $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 if ($undefined) {
223 $result['undefined_fields'] = array_merge($undefined);
224 }
225 }
226 if (is_object($dao)) {
227 $dao->free();
228 }
229
230 $result['version'] = 3;
231 if (is_array($values)) {
232 $result['count'] = (int) count($values);
233
234 // Convert value-separated strings to array
235 _civicrm_api3_separate_values($values);
236
237 if ($result['count'] == 1) {
238 list($result['id']) = array_keys($values);
239 }
240 elseif (!empty($values['id']) && is_int($values['id'])) {
241 $result['id'] = $values['id'];
242 }
243 }
244 else {
245 $result['count'] = !empty($values) ? 1 : 0;
246 }
247
248 if (is_array($values) && isset($params['sequential']) &&
249 $params['sequential'] == 1
250 ) {
251 $result['values'] = array_values($values);
252 }
253 else {
254 $result['values'] = $values;
255 }
256
257 return array_merge($result, $extraReturnValues);
258 }
259
260 /**
261 * Load the DAO of the entity
262 */
263 function _civicrm_api3_load_DAO($entity) {
264 $dao = _civicrm_api3_get_DAO($entity);
265 if (empty($dao)) {
266 return FALSE;
267 }
268 $d = new $dao();
269 return $d;
270 }
271
272 /**
273 * Function to return the DAO of the function or Entity
274 * @param String $name either a function of the api (civicrm_{entity}_create or the entity name
275 * return the DAO name to manipulate this function
276 * eg. "civicrm_api3_contact_create" or "Contact" will return "CRM_Contact_BAO_Contact"
277 * @return mixed|string
278 */
279 function _civicrm_api3_get_DAO($name) {
280 if (strpos($name, 'civicrm_api3') !== FALSE) {
281 $last = strrpos($name, '_');
282 // len ('civicrm_api3_') == 13
283 $name = substr($name, 13, $last - 13);
284 }
285
286 $name = _civicrm_api_get_camel_name($name, 3);
287
288 if ($name == 'Individual' || $name == 'Household' || $name == 'Organization') {
289 $name = 'Contact';
290 }
291
292 // hack to deal with incorrectly named BAO/DAO - see CRM-10859
293
294 // FIXME: DAO should be renamed CRM_Mailing_DAO_MailingRecipients
295 // but am not confident mailing_recipients is tested so have not tackled.
296 if ($name == 'MailingRecipients') {
297 return 'CRM_Mailing_DAO_Recipients';
298 }
299 // FIXME: DAO should be renamed CRM_Mailing_DAO_MailingComponent
300 if ($name == 'MailingComponent') {
301 return 'CRM_Mailing_DAO_Component';
302 }
303 // FIXME: DAO should be renamed CRM_ACL_DAO_AclRole
304 if ($name == 'AclRole') {
305 return 'CRM_ACL_DAO_EntityRole';
306 }
307 // FIXME: DAO should be renamed CRM_SMS_DAO_SmsProvider
308 // But this would impact SMS extensions so need to coordinate
309 // Probably best approach is to migrate them to use the api and decouple them from core BAOs
310 if ($name == 'SmsProvider') {
311 return 'CRM_SMS_DAO_Provider';
312 }
313 // FIXME: DAO names should follow CamelCase convention
314 if ($name == 'Im' || $name == 'Acl') {
315 $name = strtoupper($name);
316 }
317 return CRM_Core_DAO_AllCoreTables::getFullName($name);
318 }
319
320 /**
321 * Function to return the DAO of the function or Entity
322 * @param String $name is either a function of the api (civicrm_{entity}_create or the entity name
323 * return the DAO name to manipulate this function
324 * eg. "civicrm_contact_create" or "Contact" will return "CRM_Contact_BAO_Contact"
325 * @return mixed
326 */
327 function _civicrm_api3_get_BAO($name) {
328 // FIXME: DAO should be renamed CRM_Badge_DAO_BadgeLayout
329 if ($name == 'PrintLabel') {
330 return 'CRM_Badge_BAO_Layout';
331 }
332 $dao = _civicrm_api3_get_DAO($name);
333 if (!$dao) {
334 return NULL;
335 }
336 $bao = str_replace("DAO", "BAO", $dao);
337 $file = strtr($bao, '_', '/') . '.php';
338 // Check if this entity actually has a BAO. Fall back on the DAO if not.
339 return stream_resolve_include_path($file) ? $bao : $dao;
340 }
341
342 /**
343 * Recursive function to explode value-separated strings into arrays
344 *
345 */
346 function _civicrm_api3_separate_values(&$values) {
347 $sp = CRM_Core_DAO::VALUE_SEPARATOR;
348 foreach ($values as $key => & $value) {
349 if (is_array($value)) {
350 _civicrm_api3_separate_values($value);
351 }
352 elseif (is_string($value)) {
353 if($key == 'case_type_id'){// this is to honor the way case API was originally written
354 $value = trim(str_replace($sp, ',', $value), ',');
355 }
356 elseif (strpos($value, $sp) !== FALSE) {
357 $value = explode($sp, trim($value, $sp));
358 }
359 }
360 }
361 }
362
363 /**
364 * This is a legacy wrapper for api_store_values which will check the suitable fields using getfields
365 * rather than DAO->fields
366 *
367 * Getfields has handling for how to deal with uniquenames which dao->fields doesn't
368 *
369 * Note this is used by BAO type create functions - eg. contribution
370 * @param string $entity
371 * @param array $params
372 * @param array $values
373 */
374 function _civicrm_api3_filter_fields_for_bao($entity, &$params, &$values){
375 $fields = civicrm_api($entity,'getfields', array('version' => 3,'action' => 'create'));
376 $fields = $fields['values'];
377 _civicrm_api3_store_values($fields, $params, $values);
378 }
379 /**
380 *
381 * @param array $fields
382 * @param array $params
383 * @param array $values
384 *
385 * @return Bool $valueFound
386 */
387 function _civicrm_api3_store_values(&$fields, &$params, &$values) {
388 $valueFound = FALSE;
389
390 $keys = array_intersect_key($params, $fields);
391 foreach ($keys as $name => $value) {
392 if ($name !== 'id') {
393 $values[$name] = $value;
394 $valueFound = TRUE;
395 }
396 }
397 return $valueFound;
398 }
399
400 /**
401 * The API supports 2 types of get requestion. The more complex uses the BAO query object.
402 * This is a generic function for those functions that call it
403 *
404 * At the moment only called by contact we should extend to contribution &
405 * others that use the query object. Note that this function passes permission information in.
406 * The others don't
407 *
408 * @param $entity
409 * @param array $params as passed into api get or getcount function
410 * @param array $additional_options
411 * @param bool $getCount are we just after the count
412 *
413 * @return
414 * @internal param array $options array of options (so we can modify the filter)
415 */
416 function _civicrm_api3_get_using_query_object($entity, $params, $additional_options = array(), $getCount = NULL){
417
418 // Convert id to e.g. contact_id
419 if (empty($params[$entity . '_id']) && isset($params['id'])) {
420 $params[$entity . '_id'] = $params['id'];
421 }
422 unset($params['id']);
423
424 $options = _civicrm_api3_get_options_from_params($params, TRUE);
425
426 $inputParams = array_merge(
427 CRM_Utils_Array::value('input_params', $options, array()),
428 CRM_Utils_Array::value('input_params', $additional_options, array())
429 );
430 $returnProperties = array_merge(
431 CRM_Utils_Array::value('return', $options, array()),
432 CRM_Utils_Array::value('return', $additional_options, array())
433 );
434 if(empty($returnProperties)){
435 $returnProperties = NULL;
436 }
437 if(!empty($params['check_permissions'])){
438 // we will filter query object against getfields
439 $fields = civicrm_api($entity, 'getfields', array('version' => 3, 'action' => 'get'));
440 // we need to add this in as earlier in this function 'id' was unset in favour of $entity_id
441 $fields['values'][$entity . '_id'] = array();
442 $varsToFilter = array('returnProperties', 'inputParams');
443 foreach ($varsToFilter as $varToFilter){
444 if(!is_array($$varToFilter)){
445 continue;
446 }
447 //I was going to throw an exception rather than silently filter out - but
448 //would need to diff out of exceptions arr other keys like 'options', 'return', 'api. etcetc
449 //so we are silently ignoring parts of their request
450 //$exceptionsArr = array_diff(array_keys($$varToFilter), array_keys($fields['values']));
451 $$varToFilter = array_intersect_key($$varToFilter, $fields['values']);
452 }
453 }
454 $options = array_merge($options,$additional_options);
455 $sort = CRM_Utils_Array::value('sort', $options, NULL);
456 $offset = CRM_Utils_Array::value('offset', $options, NULL);
457 $limit = CRM_Utils_Array::value('limit', $options, NULL);
458 $smartGroupCache = CRM_Utils_Array::value('smartGroupCache', $params);
459
460 if($getCount){
461 $limit = NULL;
462 $returnProperties = NULL;
463 }
464
465 $newParams = CRM_Contact_BAO_Query::convertFormValues($inputParams);
466 foreach ($newParams as &$newParam) {
467 if($newParam[1] == '=' && is_array($newParam[2])) {
468 // we may be looking at an attempt to use the 'IN' style syntax
469 // @todo at time of writing only 'IN' & 'NOT IN' are supported for the array style syntax
470 $sqlFilter = CRM_Core_DAO::createSqlFilter($newParam[0], $params[$newParam[0]], 'String', NULL, TRUE);
471 if($sqlFilter) {
472 $newParam[1] = key($newParam[2]);
473 $newParam[2] = $sqlFilter;
474 }
475 }
476
477 }
478 $skipPermissions = !empty($params['check_permissions']) ? 0 :1;
479
480 list($entities, $options) = CRM_Contact_BAO_Query::apiQuery(
481 $newParams,
482 $returnProperties,
483 NULL,
484 $sort,
485 $offset ,
486 $limit,
487 $smartGroupCache,
488 $getCount,
489 $skipPermissions
490 );
491 if ($getCount) { // only return the count of contacts
492 return $entities;
493 }
494
495 return $entities;
496 }
497
498 /**
499 * Function transfers the filters being passed into the DAO onto the params object
500 */
501 function _civicrm_api3_dao_set_filter(&$dao, $params, $unique = TRUE, $entity) {
502 $entity = substr($dao->__table, 8);
503
504 $allfields = _civicrm_api3_build_fields_array($dao, $unique);
505
506 $fields = array_intersect(array_keys($allfields), array_keys($params));
507 if (isset($params[$entity . "_id"])) {
508 //if entity_id is set then treat it as ID (will be overridden by id if set)
509 $dao->id = $params[$entity . "_id"];
510 }
511
512 $options = _civicrm_api3_get_options_from_params($params);
513 //apply options like sort
514 _civicrm_api3_apply_options_to_dao($params, $dao, $entity);
515
516 //accept filters like filter.activity_date_time_high
517 // std is now 'filters' => ..
518 if (strstr(implode(',', array_keys($params)), 'filter')) {
519 if (isset($params['filters']) && is_array($params['filters'])) {
520 foreach ($params['filters'] as $paramkey => $paramvalue) {
521 _civicrm_api3_apply_filters_to_dao($paramkey, $paramvalue, $dao);
522 }
523 }
524 else {
525 foreach ($params as $paramkey => $paramvalue) {
526 if (strstr($paramkey, 'filter')) {
527 _civicrm_api3_apply_filters_to_dao(substr($paramkey, 7), $paramvalue, $dao);
528 }
529 }
530 }
531 }
532 // http://issues.civicrm.org/jira/browse/CRM-9150 - stick with 'simple' operators for now
533 // support for other syntaxes is discussed in ticket but being put off for now
534 $acceptedSQLOperators = array('=', '<=', '>=', '>', '<', 'LIKE', "<>", "!=", "NOT LIKE", 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN');
535 if (!$fields) {
536 $fields = array();
537 }
538
539 foreach ($fields as $field) {
540 if (is_array($params[$field])) {
541 //get the actual fieldname from db
542 $fieldName = $allfields[$field]['name'];
543 $where = CRM_Core_DAO::createSqlFilter($fieldName, $params[$field], 'String');
544 if(!empty($where)) {
545 $dao->whereAdd($where);
546 }
547 }
548 else {
549 if ($unique) {
550 $daoFieldName = $allfields[$field]['name'];
551 if (empty($daoFieldName)) {
552 throw new API_Exception("Failed to determine field name for \"$field\"");
553 }
554 $dao->{$daoFieldName} = $params[$field];
555 }
556 else {
557 $dao->$field = $params[$field];
558 }
559 }
560 }
561 if (!empty($options['return']) && is_array($options['return']) && empty($options['is_count'])) {
562 $dao->selectAdd();
563 $options['return']['id'] = TRUE;// ensure 'id' is included
564 $allfields = _civicrm_api3_get_unique_name_array($dao);
565 $returnMatched = array_intersect(array_keys($options['return']), $allfields);
566 foreach ($returnMatched as $returnValue) {
567 $dao->selectAdd($returnValue);
568 }
569
570 $unmatchedFields = array_diff(// not already matched on the field names
571 array_keys($options['return']),
572 $returnMatched
573 );
574
575 $returnUniqueMatched = array_intersect(
576 $unmatchedFields,
577 array_flip($allfields)// but a match for the field keys
578 );
579 foreach ($returnUniqueMatched as $uniqueVal){
580 $dao->selectAdd($allfields[$uniqueVal]);
581 }
582 }
583 }
584
585 /**
586 * Apply filters (e.g. high, low) to DAO object (prior to find)
587 * @param string $filterField field name of filter
588 * @param string $filterValue field value of filter
589 * @param object $dao DAO object
590 */
591 function _civicrm_api3_apply_filters_to_dao($filterField, $filterValue, &$dao) {
592 if (strstr($filterField, 'high')) {
593 $fieldName = substr($filterField, 0, -5);
594 $dao->whereAdd("($fieldName <= $filterValue )");
595 }
596 if (strstr($filterField, 'low')) {
597 $fieldName = substr($filterField, 0, -4);
598 $dao->whereAdd("($fieldName >= $filterValue )");
599 }
600 if($filterField == 'is_current' && $filterValue == 1){
601 $todayStart = date('Ymd000000', strtotime('now'));
602 $todayEnd = date('Ymd235959', strtotime('now'));
603 $dao->whereAdd("(start_date <= '$todayStart' OR start_date IS NULL) AND (end_date >= '$todayEnd' OR end_date IS NULL)");
604 if(property_exists($dao, 'is_active')){
605 $dao->whereAdd('is_active = 1');
606 }
607 }
608 }
609
610 /**
611 * Get sort, limit etc options from the params - supporting old & new formats.
612 * get returnproperties for legacy
613 *
614 * @param array $params params array as passed into civicrm_api
615 * @param bool $queryObject - is this supporting a queryobject api (e.g contact) - if so we support more options
616 * for legacy report & return a unique fields array
617 *
618 * @param string $entity
619 * @param string $action
620 *
621 * @return array $options options extracted from params
622 */
623 function _civicrm_api3_get_options_from_params(&$params, $queryObject = FALSE, $entity = '', $action = '') {
624 $is_count = FALSE;
625 $sort = CRM_Utils_Array::value('sort', $params, 0);
626 $sort = CRM_Utils_Array::value('option.sort', $params, $sort);
627 $sort = CRM_Utils_Array::value('option_sort', $params, $sort);
628
629 $offset = CRM_Utils_Array::value('offset', $params, 0);
630 $offset = CRM_Utils_Array::value('option.offset', $params, $offset);
631 // dear PHP thought it would be a good idea to transform a.b into a_b in the get/post
632 $offset = CRM_Utils_Array::value('option_offset', $params, $offset);
633
634 $limit = CRM_Utils_Array::value('rowCount', $params, 25);
635 $limit = CRM_Utils_Array::value('option.limit', $params, $limit);
636 $limit = CRM_Utils_Array::value('option_limit', $params, $limit);
637
638 if (is_array(CRM_Utils_Array::value('options', $params))) {
639 // is count is set by generic getcount not user
640 $is_count = CRM_Utils_Array::value('is_count', $params['options']);
641 $offset = CRM_Utils_Array::value('offset', $params['options'], $offset);
642 $limit = CRM_Utils_Array::value('limit', $params['options'], $limit);
643 $sort = CRM_Utils_Array::value('sort', $params['options'], $sort);
644 }
645
646 $returnProperties = array();
647 // handle the format return =sort_name,display_name...
648 if (array_key_exists('return', $params)) {
649 if (is_array($params['return'])) {
650 $returnProperties = array_fill_keys($params['return'], 1);
651 }
652 else {
653 $returnProperties = explode(',', str_replace(' ', '', $params['return']));
654 $returnProperties = array_fill_keys($returnProperties, 1);
655 }
656 }
657 if ($entity && $action =='get') {
658 if (CRM_Utils_Array::value('id',$returnProperties)) {
659 $returnProperties[$entity . '_id'] = 1;
660 unset($returnProperties['id']);
661 }
662 switch (trim(strtolower($sort))){
663 case 'id':
664 case 'id desc':
665 case 'id asc':
666 $sort = str_replace('id', $entity . '_id',$sort);
667 }
668 }
669
670 $options = array(
671 'offset' => CRM_Utils_Rule::integer($offset) ? $offset : NULL,
672 'sort' => CRM_Utils_Rule::string($sort) ? $sort : NULL,
673 'limit' => CRM_Utils_Rule::integer($limit) ? $limit : NULL,
674 'is_count' => $is_count,
675 'return' => !empty($returnProperties) ? $returnProperties : NULL,
676 );
677
678 if ($options['sort'] && stristr($options['sort'], 'SELECT')) {
679 throw new API_Exception('invalid string in sort options');
680 }
681
682 if (!$queryObject) {
683 return $options;
684 }
685 //here comes the legacy support for $returnProperties, $inputParams e.g for contat_get
686 // if the queryobject is being used this should be used
687 $inputParams = array();
688 $legacyreturnProperties = array();
689 $otherVars = array(
690 'sort', 'offset', 'rowCount', 'options','return',
691 );
692 foreach ($params as $n => $v) {
693 if (substr($n, 0, 7) == 'return.') {
694 $legacyreturnProperties[substr($n, 7)] = $v;
695 }
696 elseif ($n == 'id') {
697 $inputParams[$entity. '_id'] = $v;
698 }
699 elseif (in_array($n, $otherVars)) {}
700 else {
701 $inputParams[$n] = $v;
702 if ($v && !is_array($v) && stristr($v, 'SELECT')) {
703 throw new API_Exception('invalid string');
704 }
705 }
706 }
707 $options['return'] = array_merge($returnProperties, $legacyreturnProperties);
708 $options['input_params'] = $inputParams;
709 return $options;
710 }
711
712 /**
713 * Apply options (e.g. sort, limit, order by) to DAO object (prior to find)
714 *
715 * @param array $params params array as passed into civicrm_api
716 * @param object $dao DAO object
717 * @param $entity
718 */
719 function _civicrm_api3_apply_options_to_dao(&$params, &$dao, $entity) {
720
721 $options = _civicrm_api3_get_options_from_params($params,FALSE,$entity);
722 if(!$options['is_count']) {
723 $dao->limit((int)$options['offset'], (int)$options['limit']);
724 if (!empty($options['sort'])) {
725 $dao->orderBy($options['sort']);
726 }
727 }
728 }
729
730 /**
731 * build fields array. This is the array of fields as it relates to the given DAO
732 * returns unique fields as keys by default but if set but can return by DB fields
733 */
734 function _civicrm_api3_build_fields_array(&$bao, $unique = TRUE) {
735 $fields = $bao->fields();
736 if ($unique) {
737 if(!CRM_Utils_Array::value('id', $fields)){
738 $entity = _civicrm_api_get_entity_name_from_dao($bao);
739 $fields['id'] = $fields[$entity . '_id'];
740 unset($fields[$entity . '_id']);
741 }
742 return $fields;
743 }
744
745 foreach ($fields as $field) {
746 $dbFields[$field['name']] = $field;
747 }
748 return $dbFields;
749 }
750
751 /**
752 * build fields array. This is the array of fields as it relates to the given DAO
753 * returns unique fields as keys by default but if set but can return by DB fields
754 */
755 function _civicrm_api3_get_unique_name_array(&$bao) {
756 $fields = $bao->fields();
757 foreach ($fields as $field => $values) {
758 $uniqueFields[$field] = CRM_Utils_Array::value('name',$values, $field);
759 }
760 return $uniqueFields;
761 }
762
763 /**
764 * Converts an DAO object to an array
765 *
766 * @param object $dao (reference )object to convert
767 * @param null $params
768 * @param bool $uniqueFields
769 * @param string $entity
770 *
771 * @return array
772 *
773 * @params array of arrays (key = id) of array of fields
774 *
775 * @static void
776 * @access public
777 */
778 function _civicrm_api3_dao_to_array($dao, $params = NULL, $uniqueFields = TRUE, $entity = "") {
779 $result = array();
780 if(isset($params['options']) && CRM_Utils_Array::value('is_count', $params['options'])) {
781 return $dao->count();
782 }
783 if (empty($dao) || !$dao->find()) {
784 return array();
785 }
786
787 if(isset($dao->count)) {
788 return $dao->count;
789 }
790 //if custom fields are required we will endeavour to set them . NB passing $entity in might be a bit clunky / unrequired
791 if (!empty($entity) && CRM_Utils_Array::value('return', $params) && is_array($params['return'])) {
792 foreach ($params['return'] as $return) {
793 if (substr($return, 0, 6) == 'custom') {
794 $custom = TRUE;
795 }
796 }
797 }
798
799
800 $fields = array_keys(_civicrm_api3_build_fields_array($dao, $uniqueFields));
801
802 while ($dao->fetch()) {
803 $tmp = array();
804 foreach ($fields as $key) {
805 if (array_key_exists($key, $dao)) {
806 // not sure on that one
807 if ($dao->$key !== NULL) {
808 $tmp[$key] = $dao->$key;
809 }
810 }
811 }
812 $result[$dao->id] = $tmp;
813 if (!empty($custom)) {
814 _civicrm_api3_custom_data_get($result[$dao->id], $entity, $dao->id);
815 }
816 }
817
818
819 return $result;
820 }
821
822 /**
823 * Converts an object to an array
824 *
825 * @param object $dao (reference) object to convert
826 * @param array $values (reference) array
827 * @param array|bool $uniqueFields
828 *
829 * @return array
830 * @static void
831 * @access public
832 */
833 function _civicrm_api3_object_to_array(&$dao, &$values, $uniqueFields = FALSE) {
834
835 $fields = _civicrm_api3_build_fields_array($dao, $uniqueFields);
836 foreach ($fields as $key => $value) {
837 if (array_key_exists($key, $dao)) {
838 $values[$key] = $dao->$key;
839 }
840 }
841 }
842
843 /**
844 * Wrapper for _civicrm_object_to_array when api supports unique fields
845 */
846 function _civicrm_api3_object_to_array_unique_fields(&$dao, &$values) {
847 return _civicrm_api3_object_to_array($dao, $values, TRUE);
848 }
849
850 /**
851 *
852 * @param array $params
853 * @param array $values
854 * @param string $extends entity that this custom field extends (e.g. contribution, event, contact)
855 * @param string $entityId ID of entity per $extends
856 */
857 function _civicrm_api3_custom_format_params($params, &$values, $extends, $entityId = NULL) {
858 $values['custom'] = array();
859 foreach ($params as $key => $value) {
860 list($customFieldID, $customValueID) = CRM_Core_BAO_CustomField::getKeyID($key, TRUE);
861 if ($customFieldID && (!IS_NULL($value))) {
862 CRM_Core_BAO_CustomField::formatCustomField($customFieldID, $values['custom'],
863 $value, $extends, $customValueID, $entityId, FALSE, FALSE
864 );
865 }
866 }
867 }
868
869 /**
870 * @deprecated
871 * This function ensures that we have the right input parameters
872 *
873 * This function is only called when $dao is passed into verify_mandatory.
874 * The practice of passing $dao into verify_mandatory turned out to be
875 * unsatisfactory as the required fields @ the dao level is so diffent to the abstract
876 * api level. Hence the intention is to remove this function
877 * & the associated param from viery_mandatory
878 *
879 * @param array $params Associative array of property name/value
880 * pairs to insert in new history.
881 * @param $daoName
882 * @param bool $return
883 *
884 * @daoName string DAO to check params agains
885 *
886 * @return bool should the missing fields be returned as an array (core error created as default)
887 *
888 * @return bool true if all fields present, depending on $result a core error is created of an array of missing fields is returned
889 * @access public
890 */
891 function _civicrm_api3_check_required_fields($params, $daoName, $return = FALSE) {
892 //@deprecated - see notes
893 if (isset($params['extends'])) {
894 if (($params['extends'] == 'Activity' ||
895 $params['extends'] == 'Phonecall' ||
896 $params['extends'] == 'Meeting' ||
897 $params['extends'] == 'Group' ||
898 $params['extends'] == 'Contribution'
899 ) &&
900 ($params['style'] == 'Tab')
901 ) {
902 return civicrm_api3_create_error(ts("Can not create Custom Group in Tab for " . $params['extends']));
903 }
904 }
905
906 $dao = new $daoName();
907 $fields = $dao->fields();
908
909 $missing = array();
910 foreach ($fields as $k => $v) {
911 if ($v['name'] == 'id') {
912 continue;
913 }
914
915 if (CRM_Utils_Array::value('required', $v)) {
916 // 0 is a valid input for numbers, CRM-8122
917 if (!isset($params[$k]) || (empty($params[$k]) && !($params[$k] === 0))) {
918 $missing[] = $k;
919 }
920 }
921 }
922
923 if (!empty($missing)) {
924 if (!empty($return)) {
925 return $missing;
926 }
927 else {
928 return civicrm_api3_create_error(ts("Required fields " . implode(',', $missing) . " for $daoName are not present"));
929 }
930 }
931
932 return TRUE;
933 }
934
935 /**
936 * Check permissions for a given API call.
937 *
938 * @param $entity string API entity being accessed
939 * @param $action string API action being performed
940 * @param $params array params of the API call
941 * @param $throw deprecated bool whether to throw exception instead of returning false
942 *
943 * @throws Exception
944 * @return bool whether the current API user has the permission to make the call
945 */
946 function _civicrm_api3_api_check_permission($entity, $action, &$params, $throw = TRUE) {
947 // return early unless we’re told explicitly to do the permission check
948 if (empty($params['check_permissions']) or $params['check_permissions'] == FALSE) {
949 return TRUE;
950 }
951
952 require_once 'CRM/Core/DAO/permissions.php';
953 $permissions = _civicrm_api3_permissions($entity, $action, $params);
954
955 // $params might’ve been reset by the alterAPIPermissions() hook
956 if (isset($params['check_permissions']) and $params['check_permissions'] == FALSE) {
957 return TRUE;
958 }
959
960 if (!CRM_Core_Permission::check($permissions)) {
961 if ($throw) {
962 if(is_array($permissions)) {
963 $permissions = implode(' and ', $permissions);
964 }
965 throw new Exception("API permission check failed for $entity/$action call; insufficient permission: require $permissions");
966 }
967 else {
968 //@todo remove this - this is an internal api function called with $throw set to TRUE. It is only called with false
969 // in tests & that should be tidied up
970 return FALSE;
971 }
972 }
973
974 return TRUE;
975 }
976
977 /**
978 * Function to do a 'standard' api get - when the api is only doing a $bao->find then use this
979 *
980 * @param string $bao_name name of BAO
981 * @param array $params params from api
982 * @param bool $returnAsSuccess return in api success format
983 * @param string $entity
984 *
985 * @return array
986 */
987 function _civicrm_api3_basic_get($bao_name, &$params, $returnAsSuccess = TRUE, $entity = "") {
988 $bao = new $bao_name();
989 _civicrm_api3_dao_set_filter($bao, $params, TRUE,$entity);
990 if ($returnAsSuccess) {
991 return civicrm_api3_create_success(_civicrm_api3_dao_to_array($bao, $params, FALSE, $entity), $params, $entity);
992 }
993 else {
994 return _civicrm_api3_dao_to_array($bao, $params, FALSE, $entity);
995 }
996 }
997
998 /**
999 * Function to do a 'standard' api create - when the api is only doing a $bao::create then use this
1000 * @param string $bao_name Name of BAO Class
1001 * @param array $params parameters passed into the api call
1002 * @param string $entity Entity - pass in if entity is non-standard & required $ids array
1003 * @return array
1004 */
1005 function _civicrm_api3_basic_create($bao_name, &$params, $entity = NULL) {
1006
1007 $args = array(&$params);
1008 if (!empty($entity)) {
1009 $ids = array($entity => CRM_Utils_Array::value('id', $params));
1010 $args[] = &$ids;
1011 }
1012
1013 if (method_exists($bao_name, 'create')) {
1014 $fct = 'create';
1015 $fct_name = $bao_name . '::' . $fct;
1016 $bao = call_user_func_array(array($bao_name, $fct), $args);
1017 }
1018 elseif (method_exists($bao_name, 'add')) {
1019 $fct = 'add';
1020 $fct_name = $bao_name . '::' . $fct;
1021 $bao = call_user_func_array(array($bao_name, $fct), $args);
1022 }
1023 else {
1024 $fct_name = '_civicrm_api3_basic_create_fallback';
1025 $bao = _civicrm_api3_basic_create_fallback($bao_name, $params);
1026 }
1027
1028 if (is_null($bao)) {
1029 return civicrm_api3_create_error('Entity not created (' . $fct_name . ')');
1030 }
1031 elseif (is_a($bao, 'CRM_Core_Error')) {
1032 //some wierd circular thing means the error takes itself as an argument
1033 $msg = $bao->getMessages($bao);
1034 // the api deals with entities on a one-by-one basis. However, the contribution bao pushes entities
1035 // onto the error object - presumably because the contribution import is not handling multiple errors correctly
1036 // so we need to reset the error object here to avoid getting concatenated errors
1037 //@todo - the mulitple error handling should be moved out of the contribution object to the import / multiple entity processes
1038 CRM_Core_Error::singleton()->reset();
1039 throw new API_Exception($msg);
1040 }
1041 else {
1042 $values = array();
1043 _civicrm_api3_object_to_array($bao, $values[$bao->id]);
1044 return civicrm_api3_create_success($values, $params, $entity, 'create', $bao);
1045 }
1046 }
1047
1048 /**
1049 * For BAO's which don't have a create() or add() functions, use this fallback implementation.
1050 *
1051 * @fixme There's an intuitive sense that this behavior should be defined somehow in the BAO/DAO class
1052 * structure. In practice, that requires a fair amount of refactoring and/or kludgery.
1053 *
1054 * @param string $bao_name
1055 * @param array $params
1056 *
1057 * @throws API_Exception
1058 * @return CRM_Core_DAO|NULL an instance of the BAO
1059 */
1060 function _civicrm_api3_basic_create_fallback($bao_name, &$params) {
1061 $dao_name = get_parent_class($bao_name);
1062 if ($dao_name === 'CRM_Core_DAO' || !$dao_name) {
1063 $dao_name = $bao_name;
1064 }
1065 $entityName = CRM_Core_DAO_AllCoreTables::getBriefName($dao_name);
1066 if (empty($entityName)) {
1067 throw new API_Exception("Class \"$bao_name\" does not map to an entity name", "unmapped_class_to_entity", array(
1068 'class_name' => $bao_name,
1069 ));
1070 }
1071 $hook = empty($params['id']) ? 'create' : 'edit';
1072
1073 CRM_Utils_Hook::pre($hook, $entityName, CRM_Utils_Array::value('id', $params), $params);
1074 $instance = new $dao_name();
1075 $instance->copyValues($params);
1076 $instance->save();
1077 CRM_Utils_Hook::post($hook, $entityName, $instance->id, $instance);
1078
1079 return $instance;
1080 }
1081
1082 /**
1083 * Function to do a 'standard' api del - when the api is only doing a $bao::del then use this
1084 * if api::del doesn't exist it will try DAO delete method
1085 */
1086 function _civicrm_api3_basic_delete($bao_name, &$params) {
1087
1088 civicrm_api3_verify_mandatory($params, NULL, array('id'));
1089 $args = array(&$params['id']);
1090 if (method_exists($bao_name, 'del')) {
1091 $bao = call_user_func_array(array($bao_name, 'del'), $args);
1092 if ($bao !== FALSE) {
1093 return civicrm_api3_create_success(TRUE);
1094 }
1095 throw new API_Exception('Could not delete entity id ' . $params['id']);
1096 }
1097 elseif (method_exists($bao_name, 'delete')) {
1098 $dao = new $bao_name();
1099 $dao->id = $params['id'];
1100 if ($dao->find()) {
1101 while ($dao->fetch()) {
1102 $dao->delete();
1103 return civicrm_api3_create_success();
1104 }
1105 }
1106 else {
1107 throw new API_Exception('Could not delete entity id ' . $params['id']);
1108 }
1109 }
1110
1111 throw new API_Exception('no delete method found');
1112 }
1113
1114 /**
1115 * Get custom data for the given entity & Add it to the returnArray as 'custom_123' = 'custom string' AND 'custom_123_1' = 'custom string'
1116 * Where 123 is field value & 1 is the id within the custom group data table (value ID)
1117 *
1118 * @param array $returnArray - array to append custom data too - generally $result[4] where 4 is the entity id.
1119 * @param string $entity e.g membership, event
1120 * @param $entity_id
1121 * @param int $groupID - per CRM_Core_BAO_CustomGroup::getTree
1122 * @param int $subType e.g. membership_type_id where custom data doesn't apply to all membership types
1123 * @param string $subName - Subtype of entity
1124 */
1125 function _civicrm_api3_custom_data_get(&$returnArray, $entity, $entity_id, $groupID = NULL, $subType = NULL, $subName = NULL) {
1126 $groupTree = &CRM_Core_BAO_CustomGroup::getTree($entity,
1127 CRM_Core_DAO::$_nullObject,
1128 $entity_id,
1129 $groupID,
1130 $subType,
1131 $subName
1132 );
1133 $groupTree = CRM_Core_BAO_CustomGroup::formatGroupTree($groupTree, 1, CRM_Core_DAO::$_nullObject);
1134 $customValues = array();
1135 CRM_Core_BAO_CustomGroup::setDefaults($groupTree, $customValues);
1136 if (!empty($customValues)) {
1137 foreach ($customValues as $key => $val) {
1138 if (strstr($key, '_id')) {
1139 $idkey = substr($key, 0, -3);
1140 $returnArray['custom_' . (CRM_Core_BAO_CustomField::getKeyID($idkey) . "_id")] = $val;
1141 $returnArray[$key] = $val;
1142 }
1143 else {
1144 // per standard - return custom_fieldID
1145 $returnArray['custom_' . (CRM_Core_BAO_CustomField::getKeyID($key))] = $val;
1146
1147 //not standard - but some api did this so guess we should keep - cheap as chips
1148 $returnArray[$key] = $val;
1149 }
1150 }
1151 }
1152 }
1153
1154 /**
1155 * Validate fields being passed into API. This function relies on the getFields function working accurately
1156 * for the given API. If error mode is set to TRUE then it will also check
1157 * foreign keys
1158 *
1159 * As of writing only date was implemented.
1160 * @param string $entity
1161 * @param string $action
1162 * @param array $params -
1163 * @param array $fields response from getfields all variables are the same as per civicrm_api
1164 * @param bool $errorMode errorMode do intensive post fail checks?
1165 * @throws Exception
1166 */
1167 function _civicrm_api3_validate_fields($entity, $action, &$params, $fields, $errorMode = False) {
1168 $fields = array_intersect_key($fields, $params);
1169 foreach ($fields as $fieldName => $fieldInfo) {
1170 switch (CRM_Utils_Array::value('type', $fieldInfo)) {
1171 case CRM_Utils_Type::T_INT:
1172 //field is of type integer
1173 _civicrm_api3_validate_integer($params, $fieldName, $fieldInfo, $entity);
1174 break;
1175
1176 case 4:
1177 case 12:
1178 //field is of type date or datetime
1179 _civicrm_api3_validate_date($params, $fieldName, $fieldInfo);
1180 break;
1181
1182 case 32://blob
1183 _civicrm_api3_validate_html($params, $fieldName, $fieldInfo);
1184 break;
1185
1186 case CRM_Utils_Type::T_STRING:
1187 _civicrm_api3_validate_string($params, $fieldName, $fieldInfo, $entity);
1188 break;
1189
1190 case CRM_Utils_Type::T_MONEY:
1191 if (!CRM_Utils_Rule::money($params[$fieldName]) && !empty($params[$fieldName])) {
1192 throw new Exception($fieldName . " is not a valid amount: " . $params[$fieldName]);
1193 }
1194 }
1195
1196 // intensive checks - usually only called after DB level fail
1197 if (!empty($errorMode) && strtolower($action) == 'create') {
1198 if (CRM_Utils_Array::value('FKClassName', $fieldInfo)) {
1199 if (CRM_Utils_Array::value($fieldName, $params)) {
1200 _civicrm_api3_validate_constraint($params, $fieldName, $fieldInfo);
1201 }
1202 elseif (CRM_Utils_Array::value('required', $fieldInfo)) {
1203 throw new Exception("DB Constraint Violation - possibly $fieldName should possibly be marked as mandatory for this API. If so, please raise a bug report");
1204 }
1205 }
1206 if (CRM_Utils_Array::value('api.unique', $fieldInfo)) {
1207 $params['entity'] = $entity;
1208 _civicrm_api3_validate_uniquekey($params, $fieldName, $fieldInfo);
1209 }
1210 }
1211 }
1212 }
1213
1214 /**
1215 * Validate date fields being passed into API.
1216 * It currently converts both unique fields and DB field names to a mysql date.
1217 * @todo - probably the unique field handling & the if exists handling is now done before this
1218 * function is reached in the wrapper - can reduce this code down to assume we
1219 * are only checking the passed in field
1220 *
1221 * It also checks against the RULE:date function. This is a centralisation of code that was scattered and
1222 * may not be the best thing to do. There is no code level documentation on the existing functions to work off
1223 *
1224 * @param array $params params from civicrm_api
1225 * @param string $fieldName uniquename of field being checked
1226 * @param $fieldInfo
1227 * @throws Exception
1228 * @internal param array $fieldinfo array of fields from getfields function
1229 */
1230 function _civicrm_api3_validate_date(&$params, &$fieldName, &$fieldInfo) {
1231 //should we check first to prevent it from being copied if they have passed in sql friendly format?
1232 if (CRM_Utils_Array::value($fieldInfo['name'], $params)) {
1233 //accept 'whatever strtotime accepts
1234 if (strtotime($params[$fieldInfo['name']]) === FALSE) {
1235 throw new Exception($fieldInfo['name'] . " is not a valid date: " . $params[$fieldInfo['name']]);
1236 }
1237 $params[$fieldInfo['name']] = CRM_Utils_Date::processDate($params[$fieldInfo['name']]);
1238 }
1239 if ((CRM_Utils_Array::value('name', $fieldInfo) != $fieldName) && CRM_Utils_Array::value($fieldName, $params)) {
1240 //If the unique field name differs from the db name & is set handle it here
1241 if (strtotime($params[$fieldName]) === FALSE) {
1242 throw new Exception($fieldName . " is not a valid date: " . $params[$fieldName]);
1243 }
1244 $params[$fieldName] = CRM_Utils_Date::processDate($params[$fieldName]);
1245 }
1246 }
1247
1248 /**
1249 * Validate foreign constraint fields being passed into API.
1250 *
1251 * @param array $params params from civicrm_api
1252 * @param string $fieldName uniquename of field being checked
1253 * @param $fieldInfo
1254 * @throws Exception
1255 * @internal param array $fieldinfo array of fields from getfields function
1256 */
1257 function _civicrm_api3_validate_constraint(&$params, &$fieldName, &$fieldInfo) {
1258 $dao = new $fieldInfo['FKClassName'];
1259 $dao->id = $params[$fieldName];
1260 $dao->selectAdd();
1261 $dao->selectAdd('id');
1262 if (!$dao->find()) {
1263 throw new Exception("$fieldName is not valid : " . $params[$fieldName]);
1264 }
1265 }
1266
1267 /**
1268 * Validate foreign constraint fields being passed into API.
1269 *
1270 * @param array $params params from civicrm_api
1271 * @param string $fieldName uniquename of field being checked
1272 * @param $fieldInfo
1273 * @throws Exception
1274 * @internal param array $fieldinfo array of fields from getfields function
1275 */
1276 function _civicrm_api3_validate_uniquekey(&$params, &$fieldName, &$fieldInfo) {
1277 $existing = civicrm_api($params['entity'], 'get', array(
1278 'version' => $params['version'],
1279 $fieldName => $params[$fieldName],
1280 ));
1281 // an entry already exists for this unique field
1282 if ($existing['count'] == 1) {
1283 // question - could this ever be a security issue?
1284 throw new Exception("Field: `$fieldName` must be unique. An conflicting entity already exists - id: " . $existing['id']);
1285 }
1286 }
1287
1288 /**
1289 * Generic implementation of the "replace" action.
1290 *
1291 * Replace the old set of entities (matching some given keys) with a new set of
1292 * entities (matching the same keys).
1293 *
1294 * Note: This will verify that 'values' is present, but it does not directly verify
1295 * any other parameters.
1296 *
1297 * @param string $entity entity name
1298 * @param array $params params from civicrm_api, including:
1299 * - 'values': an array of records to save
1300 * - all other items: keys which identify new/pre-existing records
1301 * @return array|int
1302 */
1303 function _civicrm_api3_generic_replace($entity, $params) {
1304
1305 $transaction = new CRM_Core_Transaction();
1306 try {
1307 if (!is_array($params['values'])) {
1308 throw new Exception("Mandatory key(s) missing from params array: values");
1309 }
1310
1311 // Extract the keys -- somewhat scary, don't think too hard about it
1312 $baseParams = _civicrm_api3_generic_replace_base_params($params);
1313
1314 // Lookup pre-existing records
1315 $preexisting = civicrm_api($entity, 'get', $baseParams, $params);
1316 if (civicrm_error($preexisting)) {
1317 $transaction->rollback();
1318 return $preexisting;
1319 }
1320
1321 // Save the new/updated records
1322 $creates = array();
1323 foreach ($params['values'] as $replacement) {
1324 // Sugar: Don't force clients to duplicate the 'key' data
1325 $replacement = array_merge($baseParams, $replacement);
1326 $action = (isset($replacement['id']) || isset($replacement[$entity . '_id'])) ? 'update' : 'create';
1327 $create = civicrm_api($entity, $action, $replacement);
1328 if (civicrm_error($create)) {
1329 $transaction->rollback();
1330 return $create;
1331 }
1332 foreach ($create['values'] as $entity_id => $entity_value) {
1333 $creates[$entity_id] = $entity_value;
1334 }
1335 }
1336
1337 // Remove stale records
1338 $staleIDs = array_diff(
1339 array_keys($preexisting['values']),
1340 array_keys($creates)
1341 );
1342 foreach ($staleIDs as $staleID) {
1343 $delete = civicrm_api($entity, 'delete', array(
1344 'version' => $params['version'],
1345 'id' => $staleID,
1346 ));
1347 if (civicrm_error($delete)) {
1348 $transaction->rollback();
1349 return $delete;
1350 }
1351 }
1352
1353 return civicrm_api3_create_success($creates, $params);
1354 }
1355 catch(PEAR_Exception $e) {
1356 $transaction->rollback();
1357 return civicrm_api3_create_error($e->getMessage());
1358 }
1359 catch(Exception $e) {
1360 $transaction->rollback();
1361 return civicrm_api3_create_error($e->getMessage());
1362 }
1363 }
1364
1365 /**
1366 * @param $params
1367 *
1368 * @return mixed
1369 */
1370 function _civicrm_api3_generic_replace_base_params($params) {
1371 $baseParams = $params;
1372 unset($baseParams['values']);
1373 unset($baseParams['sequential']);
1374 unset($baseParams['options']);
1375 return $baseParams;
1376 }
1377
1378 /**
1379 * returns fields allowable by api
1380 *
1381 * @param $entity string Entity to query
1382 * @param bool $unique index by unique fields?
1383 * @param array $params
1384 *
1385 * @return array
1386 */
1387 function _civicrm_api_get_fields($entity, $unique = FALSE, &$params = array(
1388 )) {
1389 $unsetIfEmpty = array('dataPattern', 'headerPattern', 'default', 'export', 'import');
1390 $dao = _civicrm_api3_get_DAO($entity);
1391 if (empty($dao)) {
1392 return array();
1393 }
1394 $d = new $dao();
1395 $fields = $d->fields();
1396 // replace uniqueNames by the normal names as the key
1397 if (empty($unique)) {
1398 foreach ($fields as $name => & $field) {
1399 //getting rid of unused attributes
1400 foreach ($unsetIfEmpty as $attr) {
1401 if (empty($field[$attr])) {
1402 unset($field[$attr]);
1403 }
1404 }
1405 if ($name == $field['name']) {
1406 continue;
1407 }
1408 if (array_key_exists($field['name'], $fields)) {
1409 $field['error'] = 'name conflict';
1410 // it should never happen, but better safe than sorry
1411 continue;
1412 }
1413 $fields[$field['name']] = $field;
1414 $fields[$field['name']]['uniqueName'] = $name;
1415 unset($fields[$name]);
1416 }
1417 }
1418 $fields += _civicrm_api_get_custom_fields($entity, $params);
1419 return $fields;
1420 }
1421
1422 /**
1423 * Return an array of fields for a given entity - this is the same as the BAO function but
1424 * fields are prefixed with 'custom_' to represent api params
1425 */
1426 function _civicrm_api_get_custom_fields($entity, &$params) {
1427 $customfields = array();
1428 $entity = _civicrm_api_get_camel_name($entity);
1429 if (strtolower($entity) == 'contact') {
1430 // Use sub-type if available, otherwise stick with 'Contact'
1431 $entity = CRM_Utils_Array::value('contact_type', $params);
1432 }
1433 $retrieveOnlyParent = FALSE;
1434 // we could / should probably test for other subtypes here - e.g. activity_type_id
1435 if($entity == 'Contact'){
1436 empty($params['contact_sub_type']);
1437 }
1438 $customfields = CRM_Core_BAO_CustomField::getFields($entity,
1439 FALSE,
1440 FALSE,
1441 CRM_Utils_Array::value('contact_sub_type', $params, FALSE),
1442 NULL,
1443 $retrieveOnlyParent,
1444 FALSE,
1445 FALSE
1446 );
1447 // find out if we have any requests to resolve options
1448 $getoptions = CRM_Utils_Array::value('get_options', CRM_Utils_Array::value('options',$params));
1449 if(!is_array($getoptions)){
1450 $getoptions = array($getoptions);
1451 }
1452
1453 foreach ($customfields as $key => $value) {
1454 // Regular fields have a 'name' property
1455 $value['name'] = 'custom_' . $key;
1456 $value['type'] = _getStandardTypeFromCustomDataType($value['data_type']);
1457 $customfields['custom_' . $key] = $value;
1458 if (in_array('custom_' . $key, $getoptions)) {
1459 $customfields['custom_' . $key]['options'] = CRM_Core_BAO_CustomOption::valuesByID($key);
1460 }
1461 unset($customfields[$key]);
1462 }
1463 return $customfields;
1464 }
1465 /**
1466 * Translate the custom field data_type attribute into a std 'type'
1467 */
1468 function _getStandardTypeFromCustomDataType($dataType) {
1469 $mapping = array(
1470 'String' => CRM_Utils_Type::T_STRING,
1471 'Int' => CRM_Utils_Type::T_INT,
1472 'Money' => CRM_Utils_Type::T_MONEY,
1473 'Memo' => CRM_Utils_Type::T_LONGTEXT,
1474 'Float' => CRM_Utils_Type::T_FLOAT,
1475 'Date' => CRM_Utils_Type::T_DATE,
1476 'Boolean' => CRM_Utils_Type::T_BOOLEAN,
1477 'StateProvince' => CRM_Utils_Type::T_INT,
1478 'File' => CRM_Utils_Type::T_STRING,
1479 'Link' => CRM_Utils_Type::T_STRING,
1480 'ContactReference' => CRM_Utils_Type::T_INT,
1481 'Country' => CRM_Utils_Type::T_INT,
1482 );
1483 return $mapping[$dataType];
1484 }
1485 /**
1486 * Return array of defaults for the given API (function is a wrapper on getfields)
1487 */
1488 function _civicrm_api3_getdefaults($apiRequest, $fields) {
1489 $defaults = array();
1490
1491 foreach ($fields as $field => $values) {
1492 if (isset($values['api.default'])) {
1493 $defaults[$field] = $values['api.default'];
1494 }
1495 }
1496 return $defaults;
1497 }
1498
1499 /**
1500 * Return array of defaults for the given API (function is a wrapper on getfields)
1501 */
1502 function _civicrm_api3_getrequired($apiRequest, $fields) {
1503 $required = array('version');
1504
1505 foreach ($fields as $field => $values) {
1506 if (CRM_Utils_Array::value('api.required', $values)) {
1507 $required[] = $field;
1508 }
1509 }
1510 return $required;
1511 }
1512
1513 /**
1514 * Fill params array with alternate (alias) values where a field has an alias and that is filled & the main field isn't
1515 * If multiple aliases the last takes precedence
1516 *
1517 * Function also swaps unique fields for non-unique fields & vice versa.
1518 */
1519 function _civicrm_api3_swap_out_aliases(&$apiRequest, $fields) {
1520 foreach ($fields as $field => $values) {
1521 $uniqueName = CRM_Utils_Array::value('uniqueName', $values);
1522 if (CRM_Utils_Array::value('api.aliases', $values)) {
1523 // if aliased field is not set we try to use field alias
1524 if (!isset($apiRequest['params'][$field])) {
1525 foreach ($values['api.aliases'] as $alias) {
1526 if (isset($apiRequest['params'][$alias])) {
1527 $apiRequest['params'][$field] = $apiRequest['params'][$alias];
1528 }
1529 //unset original field nb - need to be careful with this as it may bring inconsistencies
1530 // out of the woodwork but will be implementing only as _spec function extended
1531 unset($apiRequest['params'][$alias]);
1532 }
1533 }
1534 }
1535 if (!isset($apiRequest['params'][$field])
1536 && CRM_Utils_Array::value('name', $values)
1537 && $field != $values['name']
1538 && isset($apiRequest['params'][$values['name']])
1539 ) {
1540 $apiRequest['params'][$field] = $apiRequest['params'][$values['name']];
1541 // note that it would make sense to unset the original field here but tests need to be in place first
1542 }
1543 if (!isset($apiRequest['params'][$field])
1544 && $uniqueName
1545 && $field != $uniqueName
1546 && array_key_exists($uniqueName, $apiRequest['params'])
1547 )
1548 {
1549 $apiRequest['params'][$field] = CRM_Utils_Array::value($values['uniqueName'], $apiRequest['params']);
1550 // note that it would make sense to unset the original field here but tests need to be in place first
1551 }
1552 }
1553
1554 }
1555
1556 /**
1557 * Validate integer fields being passed into API.
1558 * It currently converts the incoming value 'user_contact_id' into the id of the currenty logged in user
1559 *
1560 * @param array $params params from civicrm_api
1561 * @param string $fieldName uniquename of field being checked
1562 * @param $fieldInfo
1563 * @param $entity
1564 * @throws API_Exception
1565 * @internal param array $fieldinfo array of fields from getfields function
1566 */
1567 function _civicrm_api3_validate_integer(&$params, &$fieldName, &$fieldInfo, $entity) {
1568 //if fieldname exists in params
1569 if (CRM_Utils_Array::value($fieldName, $params)) {
1570 // if value = 'user_contact_id' (or similar), replace value with contact id
1571 if (!is_numeric($params[$fieldName]) && is_scalar($params[$fieldName])) {
1572 $realContactId = _civicrm_api3_resolve_contactID($params[$fieldName]);
1573 if ('unknown-user' === $realContactId) {
1574 throw new API_Exception("\"$fieldName\" \"{$params[$fieldName]}\" cannot be resolved to a contact ID", 2002, array('error_field' => $fieldName,"type"=>"integer"));
1575 } elseif (is_numeric($realContactId)) {
1576 $params[$fieldName] = $realContactId;
1577 }
1578 }
1579 if (!empty($fieldInfo['pseudoconstant']) || !empty($fieldInfo['options'])) {
1580 _civicrm_api3_api_match_pseudoconstant($params, $entity, $fieldName, $fieldInfo);
1581 }
1582
1583 // After swapping options, ensure we have an integer(s)
1584 foreach ((array) ($params[$fieldName]) as $value) {
1585 if ($value && !is_numeric($value) && $value !== 'null' && !is_array($value)) {
1586 throw new API_Exception("$fieldName is not a valid integer", 2001, array('error_field' => $fieldName, "type" => "integer"));
1587 }
1588 }
1589
1590 // Check our field length
1591 if(is_string($params[$fieldName]) &&
1592 CRM_Utils_Array::value('maxlength',$fieldInfo)
1593 && strlen($params[$fieldName]) > $fieldInfo['maxlength']
1594 ){
1595 throw new API_Exception( $params[$fieldName] . " is " . strlen($params[$fieldName]) . " characters - longer than $fieldName length" . $fieldInfo['maxlength'] . ' characters',
1596 2100, array('field' => $fieldName, "max_length"=>$fieldInfo['maxlength'])
1597 );
1598 }
1599 }
1600 }
1601
1602 /**
1603 * Determine a contact ID using a string expression
1604 *
1605 * @param string $contactIdExpr e.g. "user_contact_id" or "@user:username"
1606 * @return int|NULL|'unknown-user'
1607 */
1608 function _civicrm_api3_resolve_contactID($contactIdExpr) {
1609 //if value = 'user_contact_id' replace value with logged in user id
1610 if ($contactIdExpr == "user_contact_id") {
1611 $session = &CRM_Core_Session::singleton();
1612 if (!is_numeric($session->get('userID'))) {
1613 return NULL;
1614 }
1615 return $session->get('userID');
1616 } elseif (preg_match('/^@user:(.*)$/', $contactIdExpr, $matches)) {
1617 $config = CRM_Core_Config::singleton();
1618
1619 $ufID = $config->userSystem->getUfId($matches[1]);
1620 if (!$ufID) {
1621 return 'unknown-user';
1622 }
1623
1624 $contactID = CRM_Core_BAO_UFMatch::getContactId($ufID);
1625 if (!$contactID) {
1626 return 'unknown-user';
1627 }
1628
1629 return $contactID;
1630 }
1631 return NULL;
1632 }
1633
1634 /**
1635 * Validate html (check for scripting attack)
1636 * @param $params
1637 * @param $fieldName
1638 * @param $fieldInfo
1639 *
1640 * @throws API_Exception
1641 */
1642 function _civicrm_api3_validate_html(&$params, &$fieldName, &$fieldInfo) {
1643 if ($value = CRM_Utils_Array::value($fieldName, $params)) {
1644 if (!CRM_Utils_Rule::xssString($value)) {
1645 throw new API_Exception('Illegal characters in input (potential scripting attack)', array("field"=>$fieldName,"error_code"=>"xss"));
1646 }
1647 }
1648 }
1649
1650 /**
1651 * Validate string fields being passed into API.
1652 * @param array $params params from civicrm_api
1653 * @param string $fieldName uniquename of field being checked
1654 * @param $fieldInfo
1655 * @param $entity
1656 * @throws API_Exception
1657 * @throws Exception
1658 * @internal param array $fieldinfo array of fields from getfields function
1659 */
1660 function _civicrm_api3_validate_string(&$params, &$fieldName, &$fieldInfo, $entity) {
1661 // If fieldname exists in params
1662 $value = CRM_Utils_Array::value($fieldName, $params, '');
1663 if(!is_array($value)){
1664 $value = (string) $value;
1665 }
1666 else{
1667 //@todo what do we do about passed in arrays. For many of these fields
1668 // the missing piece of functionality is separating them to a separated string
1669 // & many save incorrectly. But can we change them wholesale?
1670 }
1671 if ($value ) {
1672 if (!CRM_Utils_Rule::xssString($value)) {
1673 throw new Exception('Illegal characters in input (potential scripting attack)');
1674 }
1675 if ($fieldName == 'currency') {
1676 if (!CRM_Utils_Rule::currencyCode($value)) {
1677 throw new Exception("Currency not a valid code: $value");
1678 }
1679 }
1680 if (!empty($fieldInfo['pseudoconstant']) || !empty($fieldInfo['options']) || !empty($fieldInfo['enumValues'])) {
1681 _civicrm_api3_api_match_pseudoconstant($params, $entity, $fieldName, $fieldInfo);
1682 }
1683 // Check our field length
1684 elseif (is_string($value) && !empty($fieldInfo['maxlength']) && strlen($value) > $fieldInfo['maxlength']) {
1685 throw new API_Exception("Value for $fieldName is " . strlen($value) . " characters - This field has a maxlength of {$fieldInfo['maxlength']} characters.",
1686 2100, array('field' => $fieldName)
1687 );
1688 }
1689 }
1690 }
1691
1692 /**
1693 * Validate & swap out any pseudoconstants / options
1694 *
1695 * @param $params: api parameters
1696 * @param $entity: api entity name
1697 * @param $fieldName: field name used in api call (not necessarily the canonical name)
1698 * @param $fieldInfo: getfields meta-data
1699 */
1700 function _civicrm_api3_api_match_pseudoconstant(&$params, $entity, $fieldName, $fieldInfo) {
1701 $options = CRM_Utils_Array::value('options', $fieldInfo);
1702 if (!$options) {
1703 if(strtolower($entity) == 'profile' && !empty($fieldInfo['entity'])) {
1704 // we need to get the options from the entity the field relates to
1705 $entity = $fieldInfo['entity'];
1706 }
1707 $options = civicrm_api($entity, 'getoptions', array('version' => 3, 'field' => $fieldInfo['name'], 'context' => 'validate'));
1708 $options = CRM_Utils_Array::value('values', $options, array());
1709 }
1710
1711 // If passed a value-separated string, explode to an array, then re-implode after matching values
1712 $implode = FALSE;
1713 if (is_string($params[$fieldName]) && strpos($params[$fieldName], CRM_Core_DAO::VALUE_SEPARATOR) !== FALSE) {
1714 $params[$fieldName] = CRM_Utils_Array::explodePadded($params[$fieldName]);
1715 $implode = TRUE;
1716 }
1717 // If passed multiple options, validate each
1718 if (is_array($params[$fieldName])) {
1719 foreach ($params[$fieldName] as &$value) {
1720 if (!is_array($value)) {
1721 _civicrm_api3_api_match_pseudoconstant_value($value, $options, $fieldName);
1722 }
1723 }
1724 // TODO: unwrap the call to implodePadded from the conditional and do it always
1725 // need to verify that this is safe and doesn't break anything though.
1726 // Better yet would be to leave it as an array and ensure that every dao/bao can handle array input
1727 if ($implode) {
1728 CRM_Utils_Array::implodePadded($params[$fieldName]);
1729 }
1730 }
1731 else {
1732 _civicrm_api3_api_match_pseudoconstant_value($params[$fieldName], $options, $fieldName);
1733 }
1734 }
1735
1736 /**
1737 * Validate & swap a single option value for a field
1738 *
1739 * @param $value: field value
1740 * @param $options: array of options for this field
1741 * @param $fieldName: field name used in api call (not necessarily the canonical name)
1742 * @throws API_Exception
1743 */
1744 function _civicrm_api3_api_match_pseudoconstant_value(&$value, $options, $fieldName) {
1745 // If option is a key, no need to translate
1746 if (array_key_exists($value, $options)) {
1747 return;
1748 }
1749
1750 // Translate value into key
1751 $newValue = array_search($value, $options);
1752 if ($newValue !== FALSE) {
1753 $value = $newValue;
1754 return;
1755 }
1756 // Case-insensitive matching
1757 $newValue = strtolower($value);
1758 $options = array_map("strtolower", $options);
1759 $newValue = array_search($newValue, $options);
1760 if ($newValue === FALSE) {
1761 throw new API_Exception("'$value' is not a valid option for field $fieldName", 2001, array('error_field' => $fieldName));
1762 }
1763 $value = $newValue;
1764 }
1765
1766 /**
1767 * Returns the canonical name of a field
1768 * @param $entity: api entity name (string should already be standardized - no camelCase)
1769 * @param $fieldName: any variation of a field's name (name, unique_name, api.alias)
1770 *
1771 * @return (string|bool) fieldName or FALSE if the field does not exist
1772 */
1773 function _civicrm_api3_api_resolve_alias($entity, $fieldName) {
1774 if (strpos($fieldName, 'custom_') === 0 && is_numeric($fieldName[7])) {
1775 return $fieldName;
1776 }
1777 if ($fieldName == "{$entity}_id") {
1778 return 'id';
1779 }
1780 $result = civicrm_api($entity, 'getfields', array(
1781 'version' => 3,
1782 'action' => 'create',
1783 ));
1784 $meta = $result['values'];
1785 if (!isset($meta[$fieldName]['name']) && isset($meta[$fieldName . '_id'])) {
1786 $fieldName = $fieldName . '_id';
1787 }
1788 if (isset($meta[$fieldName])) {
1789 return $meta[$fieldName]['name'];
1790 }
1791 foreach ($meta as $info) {
1792 if ($fieldName == CRM_Utils_Array::value('uniqueName', $info)) {
1793 return $info['name'];
1794 }
1795 if (array_search($fieldName, CRM_Utils_Array::value('api.aliases', $info, array())) !== FALSE) {
1796 return $info['name'];
1797 }
1798 }
1799 return FALSE;
1800 }