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