4 +--------------------------------------------------------------------+
5 | Copyright CiviCRM LLC. All rights reserved. |
7 | This work is published under the GNU AGPLv3 license with some |
8 | permitted exceptions and without any warranty. For full license |
9 | and copyright information, see https://civicrm.org/licensing |
10 +--------------------------------------------------------------------+
16 * @copyright CiviCRM LLC https://civicrm.org/licensing
19 namespace Civi\Api4\Generic
;
21 use Civi\Api4\Utils\FormattingUtil
;
22 use Civi\Api4\Utils\ReflectionUtils
;
25 * Base class for all api actions.
27 * An api Action object stores the parameters of the api call, and defines a _run function to execute the action.
29 * Every `protected` class var is considered a parameter (unless it starts with an underscore).
31 * Adding a `protected` var to your Action named e.g. `$thing` will automatically:
32 * - Provide a getter/setter (via `__call` MagicMethod) named `getThing()` and `setThing()`.
33 * - Expose the param in the Api Explorer (be sure to add a doc-block as it displays in the help panel).
34 * - Require a value for the param if you add the "@required" annotation.
36 * @method bool getCheckPermissions()
37 * @method $this setDebug(bool $value) Enable/disable debug output
38 * @method bool getDebug()
39 * @method $this setChain(array $chain)
40 * @method array getChain()
42 abstract class AbstractAction
implements \ArrayAccess
{
45 * Api version number; cannot be changed.
49 protected $version = 4;
52 * Additional api requests - will be called once per result.
54 * Keys can be any string - this will be the name given to the output.
56 * You can reference other values in the api results in this call by prefixing them with `$`.
58 * For example, you could create a contact and place them in a group by chaining the
59 * `GroupContact` api to the `Contact` api:
63 * ->setValue('first_name', 'Hello')
64 * ->addChain('add_a_group', GroupContact::create()
65 * ->setValue('contact_id', '$id')
66 * ->setValue('group_id', 123)
70 * This will substitute the id of the newly created contact with `$id`.
74 protected $chain = [];
77 * Whether to enforce acl permissions based on the current user.
79 * Setting to FALSE will disable permission checks and override ACLs.
80 * In REST/javascript this cannot be disabled.
84 protected $checkPermissions = TRUE;
87 * Add debugging info to the api result.
89 * When enabled, `$result->debug` will be populated with information about the api call,
90 * including sql queries executed.
92 * **Note:** with checkPermissions enabled, debug info will only be returned if the user has "view debug output" permission.
96 protected $debug = FALSE;
101 protected $_entityName;
106 protected $_actionName;
109 * @var \ReflectionClass
111 private $_reflection;
121 private $_entityFields;
126 private $_arrayStorage = [];
130 * Used to identify api calls for transactions
131 * @see \Civi\Core\Transaction\Manager
135 public $_debugOutput = [];
138 * Action constructor.
140 * @param string $entityName
141 * @param string $actionName
142 * @throws \API_Exception
144 public function __construct($entityName, $actionName) {
145 // If a namespaced class name is passed in
146 if (strpos($entityName, '\\') !== FALSE) {
147 $entityName = substr($entityName, strrpos($entityName, '\\') +
1);
149 $this->_entityName
= $entityName;
150 $this->_actionName
= $actionName;
151 $this->_id
= \Civi\API\Request
::getNextId();
155 * Strictly enforce api parameters
160 public function __set($name, $value) {
161 throw new \
API_Exception('Unknown api parameter');
167 * @throws \API_Exception
169 public function setVersion($val) {
170 if ($val !== 4 && $val !== '4') {
171 throw new \
API_Exception('Cannot modify api version');
177 * @param bool $checkPermissions
180 public function setCheckPermissions(bool $checkPermissions) {
181 $this->checkPermissions
= $checkPermissions;
186 * @param string $name
187 * Unique name for this chained request
188 * @param \Civi\Api4\Generic\AbstractAction $apiRequest
189 * @param string|int|array $index
190 * See `civicrm_api4()` for documentation of `$index` param
193 public function addChain($name, AbstractAction
$apiRequest, $index = NULL) {
194 $this->chain
[$name] = [$apiRequest->getEntityName(), $apiRequest->getActionName(), $apiRequest->getParams(), $index];
199 * Magic function to provide automatic getter/setter for params.
203 * @return static|mixed
204 * @throws \API_Exception
206 public function __call($name, $arguments) {
207 $param = lcfirst(substr($name, 3));
208 if (!$param ||
$param[0] == '_') {
209 throw new \
API_Exception('Unknown api parameter: ' . $name);
211 $mode = substr($name, 0, 3);
212 if ($this->paramExists($param)) {
215 return $this->$param;
218 $this->$param = $arguments[0];
222 throw new \
API_Exception('Unknown api parameter: ' . $name);
228 * At this point all the params have been sent in and we initiate the api call & return the result.
229 * This is basically the outer wrapper for api v4.
231 * @return \Civi\Api4\Generic\Result
232 * @throws \API_Exception
233 * @throws \Civi\API\Exception\UnauthorizedException
235 public function execute() {
236 /** @var \Civi\API\Kernel $kernel */
237 $kernel = \Civi
::service('civi_api_kernel');
238 $result = $kernel->runRequest($this);
239 if ($this->debug
&& (!$this->checkPermissions || \CRM_Core_Permission
::check('view debug output'))) {
240 $result->debug
['actionClass'] = get_class($this);
241 $result->debug
= array_merge($result->debug
, $this->_debugOutput
);
244 $result->debug
= NULL;
250 * @param \Civi\Api4\Generic\Result $result
252 abstract public function _run(Result
$result);
255 * Serialize this object's params into an array
258 public function getParams() {
260 foreach ($this->reflect()->getProperties(\ReflectionProperty
::IS_PROTECTED
) as $property) {
261 $name = $property->getName();
262 // Skip variables starting with an underscore
263 if ($name[0] != '_') {
264 $params[$name] = $this->$name;
271 * Get documentation for one or all params
273 * @param string $param
274 * @return array of arrays [description, type, default, (comment)]
276 public function getParamInfo($param = NULL) {
277 if (!isset($this->_paramInfo
)) {
278 $defaults = $this->getParamDefaults();
280 'entity' => $this->getEntityName(),
281 'action' => $this->getActionName(),
283 // For actions like "getFields" and "getActions" they are not getting the entity itself.
284 // So generic docs will make more sense like this:
285 if (substr($vars['action'], 0, 3) === 'get' && substr($vars['action'], -1) === 's') {
286 $vars['entity'] = lcfirst(substr($vars['action'], 3, -1));
288 foreach ($this->reflect()->getProperties(\ReflectionProperty
::IS_PROTECTED
) as $property) {
289 $name = $property->getName();
290 if ($name != 'version' && $name[0] != '_') {
291 $this->_paramInfo
[$name] = ReflectionUtils
::getCodeDocs($property, 'Property', $vars);
292 $this->_paramInfo
[$name]['default'] = $defaults[$name];
296 return $param ?
$this->_paramInfo
[$param] : $this->_paramInfo
;
302 public function getEntityName() {
303 return $this->_entityName
;
310 public function getActionName() {
311 return $this->_actionName
;
315 * @param string $param
318 public function paramExists($param) {
319 return array_key_exists($param, $this->getParams());
325 protected function getParamDefaults() {
326 return array_intersect_key($this->reflect()->getDefaultProperties(), $this->getParams());
332 public function offsetExists($offset) {
333 return in_array($offset, ['entity', 'action', 'params', 'version', 'check_permissions', 'id']) ||
isset($this->_arrayStorage
[$offset]);
339 public function &offsetGet($offset) {
341 if (in_array($offset, ['entity', 'action'])) {
344 if (in_array($offset, ['entityName', 'actionName', 'params', 'version'])) {
345 $getter = 'get' . ucfirst($offset);
346 $val = $this->$getter();
349 if ($offset == 'check_permissions') {
350 return $this->checkPermissions
;
352 if ($offset == 'id') {
355 if (isset($this->_arrayStorage
[$offset])) {
356 return $this->_arrayStorage
[$offset];
364 public function offsetSet($offset, $value) {
365 if (in_array($offset, ['entity', 'action', 'entityName', 'actionName', 'params', 'version', 'id'])) {
366 throw new \
API_Exception('Cannot modify api4 state via array access');
368 if ($offset == 'check_permissions') {
369 $this->setCheckPermissions($value);
372 $this->_arrayStorage
[$offset] = $value;
379 public function offsetUnset($offset) {
380 if (in_array($offset, ['entity', 'action', 'entityName', 'actionName', 'params', 'check_permissions', 'version', 'id'])) {
381 throw new \
API_Exception('Cannot modify api4 state via array access');
383 unset($this->_arrayStorage
[$offset]);
387 * Is this api call permitted?
389 * This function is called if checkPermissions is set to true.
393 public function isAuthorized() {
394 $permissions = $this->getPermissions();
395 return \CRM_Core_Permission
::check($permissions);
401 public function getPermissions() {
402 $permissions = call_user_func(["\\Civi\\Api4\\" . $this->_entityName
, 'permissions']);
404 // applies to getFields, getActions, etc.
405 'meta' => ['access CiviCRM'],
406 // catch-all, applies to create, get, delete, etc.
407 'default' => ['administer CiviCRM'],
409 $action = $this->getActionName();
410 if (isset($permissions[$action])) {
411 return $permissions[$action];
413 elseif (in_array($action, ['getActions', 'getFields'])) {
414 return $permissions['meta'];
416 return $permissions['default'];
420 * Returns schema fields for this entity & action.
422 * Here we bypass the api wrapper and run the getFields action directly.
423 * This is because we DON'T want the wrapper to check permissions as this is an internal op,
424 * but we DO want permissions to be checked inside the getFields request so e.g. the api_key
425 * field can be conditionally included.
426 * @see \Civi\Api4\Action\Contact\GetFields
428 * @throws \API_Exception
431 public function entityFields() {
432 if (!$this->_entityFields
) {
433 $getFields = \Civi\API\Request
::create($this->getEntityName(), 'getFields', [
435 'checkPermissions' => $this->checkPermissions
,
436 'action' => $this->getActionName(),
437 'includeCustom' => FALSE,
439 $result = new Result();
440 $getFields->_run($result);
441 $this->_entityFields
= (array) $result->indexBy('name');
443 return $this->_entityFields
;
447 * @return \ReflectionClass
449 public function reflect() {
450 if (!$this->_reflection
) {
451 $this->_reflection
= new \
ReflectionClass($this);
453 return $this->_reflection
;
457 * Validates required fields for actions which create a new object.
461 * @throws \API_Exception
463 protected function checkRequiredFields($values) {
465 foreach ($this->entityFields() as $fieldName => $fieldInfo) {
466 if (!isset($values[$fieldName]) ||
$values[$fieldName] === '') {
467 if (!empty($fieldInfo['required']) && !isset($fieldInfo['default_value'])) {
468 $unmatched[] = $fieldName;
470 elseif (!empty($fieldInfo['required_if'])) {
471 if ($this->evaluateCondition($fieldInfo['required_if'], ['values' => $values])) {
472 $unmatched[] = $fieldName;
481 * Replaces pseudoconstants in input values
483 * @param array $record
484 * @throws \API_Exception
486 protected function formatWriteValues(&$record) {
488 // Collect fieldnames with a :pseudoconstant suffix & remove them from $record array
489 foreach (array_keys($record) as $expr) {
490 $suffix = strrpos($expr, ':');
492 $fieldName = substr($expr, 0, $suffix);
493 $field = $this->entityFields()[$fieldName] ??
NULL;
495 $optionFields[$fieldName] = [
496 'val' => $record[$expr],
497 'name' => empty($field['custom_field_id']) ?
$field['name'] : 'custom_' . $field['custom_field_id'],
498 'suffix' => substr($expr, $suffix +
1),
499 'depends' => $field['input_attrs']['controlField'] ??
NULL,
501 unset($record[$expr]);
505 // Sort option lookups by dependency, so e.g. country_id is processed first, then state_province_id, then county_id
506 uasort($optionFields, function ($a, $b) {
507 return $a['name'] === $b['depends'] ?
-1 : 1;
509 // Replace pseudoconstants. Note this is a reverse lookup as we are evaluating input not output.
510 foreach ($optionFields as $fieldName => $info) {
511 $options = FormattingUtil
::getPseudoconstantList($this->_entityName
, $info['name'], $info['suffix'], $record, 'create');
512 $record[$fieldName] = FormattingUtil
::replacePseudoconstant($options, $info['val'], TRUE);
517 * This function is used internally for evaluating field annotations.
519 * It should never be passed raw user input.
521 * @param string $expr
522 * Conditional in php format e.g. $foo > $bar
524 * Variable name => value
526 * @throws \API_Exception
529 protected function evaluateCondition($expr, $vars) {
530 if (strpos($expr, '}') !== FALSE ||
strpos($expr, '{') !== FALSE) {
531 throw new \
API_Exception('Illegal character in expression');
533 $tpl = "{if $expr}1{else}0{/if}";
534 return (bool) trim(\CRM_Core_Smarty
::singleton()->fetchWith('string:' . $tpl, $vars));
538 * When in debug mode, this logs the callback function being used by a Basic*Action class.
540 * @param callable $callable
542 protected function addCallbackToDebugOutput($callable) {
543 if ($this->debug
&& empty($this->_debugOutput
['callback'])) {
544 if (is_scalar($callable)) {
545 $this->_debugOutput
['callback'] = (string) $callable;
547 elseif (is_array($callable)) {
548 foreach ($callable as $key => $unit) {
549 $this->_debugOutput
['callback'][$key] = is_object($unit) ?
get_class($unit) : (string) $unit;
552 elseif (is_object($callable)) {
553 $this->_debugOutput
['callback'] = get_class($callable);