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