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