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 +--------------------------------------------------------------------+
12 namespace Civi\Api4\Generic
;
14 use Civi\Api4\Utils\CoreUtil
;
15 use Civi\Api4\Utils\FormattingUtil
;
16 use Civi\Api4\Utils\ReflectionUtils
;
19 * Base class for all api actions.
21 * An api Action object stores the parameters of the api call, and defines a _run function to execute the action.
23 * Every `protected` class var is considered a parameter (unless it starts with an underscore).
25 * Adding a `protected` var to your Action named e.g. `$thing` will automatically:
26 * - Provide a getter/setter (via `__call` MagicMethod) named `getThing()` and `setThing()`.
27 * - Expose the param in the Api Explorer (be sure to add a doc-block as it displays in the help panel).
28 * - Require a value for the param if you add the "@required" annotation.
30 * @method bool getCheckPermissions()
31 * @method $this setDebug(bool $value) Enable/disable debug output
32 * @method bool getDebug()
33 * @method $this setChain(array $chain)
34 * @method array getChain()
36 abstract class AbstractAction
implements \ArrayAccess
{
38 use \Civi\Schema\Traits\MagicGetterSetterTrait
;
41 * Api version number; cannot be changed.
45 protected $version = 4;
48 * Additional api requests - will be called once per result.
50 * Keys can be any string - this will be the name given to the output.
52 * You can reference other values in the api results in this call by prefixing them with `$`.
54 * For example, you could create a contact and place them in a group by chaining the
55 * `GroupContact` api to the `Contact` api:
59 * ->setValue('first_name', 'Hello')
60 * ->addChain('add_a_group', GroupContact::create()
61 * ->setValue('contact_id', '$id')
62 * ->setValue('group_id', 123)
66 * This will substitute the id of the newly created contact with `$id`.
70 protected $chain = [];
73 * Whether to enforce acl permissions based on the current user.
75 * Setting to FALSE will disable permission checks and override ACLs.
76 * In REST/javascript this cannot be disabled.
80 protected $checkPermissions = TRUE;
83 * Add debugging info to the api result.
85 * When enabled, `$result->debug` will be populated with information about the api call,
86 * including sql queries executed.
88 * **Note:** with checkPermissions enabled, debug info will only be returned if the user has "view debug output" permission.
92 protected $debug = FALSE;
97 protected $_entityName;
102 protected $_actionName;
105 * @var \ReflectionClass
107 private $_reflection;
117 private $_entityFields;
122 private $_arrayStorage = [];
126 * Used to identify api calls for transactions
127 * @see \Civi\Core\Transaction\Manager
131 public $_debugOutput = [];
134 * Action constructor.
136 * @param string $entityName
137 * @param string $actionName
138 * @throws \API_Exception
140 public function __construct($entityName, $actionName) {
141 // If a namespaced class name is passed in
142 if (strpos($entityName, '\\') !== FALSE) {
143 $entityName = substr($entityName, strrpos($entityName, '\\') +
1);
145 $this->_entityName
= $entityName;
146 $this->_actionName
= $actionName;
147 $this->_id
= \Civi\API\Request
::getNextId();
151 * Strictly enforce api parameters
156 public function __set($name, $value) {
157 throw new \
API_Exception('Unknown api parameter');
163 * @throws \API_Exception
165 public function setVersion($val) {
166 if ($val !== 4 && $val !== '4') {
167 throw new \
API_Exception('Cannot modify api version');
173 * @param bool $checkPermissions
176 public function setCheckPermissions(bool $checkPermissions) {
177 $this->checkPermissions
= $checkPermissions;
182 * @param string $name
183 * Unique name for this chained request
184 * @param \Civi\Api4\Generic\AbstractAction $apiRequest
185 * @param string|int|array $index
186 * See `civicrm_api4()` for documentation of `$index` param
189 public function addChain($name, AbstractAction
$apiRequest, $index = NULL) {
190 $this->chain
[$name] = [$apiRequest->getEntityName(), $apiRequest->getActionName(), $apiRequest->getParams(), $index];
195 * Magic function to provide automatic getter/setter for params.
199 * @return static|mixed
200 * @throws \API_Exception
202 public function __call($name, $arguments) {
203 $param = lcfirst(substr($name, 3));
204 if (!$param ||
$param[0] == '_') {
205 throw new \
API_Exception('Unknown api parameter: ' . $name);
207 $mode = substr($name, 0, 3);
208 if ($this->paramExists($param)) {
211 return $this->$param;
214 $this->$param = $arguments[0];
218 throw new \
API_Exception('Unknown api parameter: ' . $name);
224 * At this point all the params have been sent in and we initiate the api call & return the result.
225 * This is basically the outer wrapper for api v4.
227 * @return \Civi\Api4\Generic\Result
228 * @throws \API_Exception
229 * @throws \Civi\API\Exception\UnauthorizedException
231 public function execute() {
232 /** @var \Civi\API\Kernel $kernel */
233 $kernel = \Civi
::service('civi_api_kernel');
234 $result = $kernel->runRequest($this);
235 if ($this->debug
&& (!$this->checkPermissions || \CRM_Core_Permission
::check('view debug output'))) {
236 $result->debug
['actionClass'] = get_class($this);
237 $result->debug
= array_merge($result->debug
, $this->_debugOutput
);
240 $result->debug
= NULL;
246 * @param \Civi\Api4\Generic\Result $result
248 abstract public function _run(Result
$result);
251 * Serialize this object's params into an array
254 public function getParams() {
256 $magicProperties = $this->getMagicProperties();
257 foreach ($magicProperties as $name => $bool) {
258 $params[$name] = $this->$name;
264 * Get documentation for one or all params
266 * @param string $param
267 * @return array of arrays [description, type, default, (comment)]
269 public function getParamInfo($param = NULL) {
270 if (!isset($this->_paramInfo
)) {
271 $defaults = $this->getParamDefaults();
273 'entity' => $this->getEntityName(),
274 'action' => $this->getActionName(),
276 // For actions like "getFields" and "getActions" they are not getting the entity itself.
277 // So generic docs will make more sense like this:
278 if (substr($vars['action'], 0, 3) === 'get' && substr($vars['action'], -1) === 's') {
279 $vars['entity'] = lcfirst(substr($vars['action'], 3, -1));
281 foreach ($this->reflect()->getProperties(\ReflectionProperty
::IS_PROTECTED
) as $property) {
282 $name = $property->getName();
283 if ($name != 'version' && $name[0] != '_') {
284 $docs = ReflectionUtils
::getCodeDocs($property, 'Property', $vars);
285 $docs['default'] = $defaults[$name];
286 if (!empty($docs['optionsCallback'])) {
287 $docs['options'] = $this->{$docs['optionsCallback']}();
288 unset($docs['optionsCallback']);
290 $this->_paramInfo
[$name] = $docs;
294 return $param ?
$this->_paramInfo
[$param] : $this->_paramInfo
;
300 public function getEntityName() {
301 return $this->_entityName
;
308 public function getActionName() {
309 return $this->_actionName
;
313 * @param string $param
316 public function paramExists($param) {
317 return array_key_exists($param, $this->getMagicProperties());
323 protected function getParamDefaults() {
324 return array_intersect_key($this->reflect()->getDefaultProperties(), $this->getMagicProperties());
330 public function offsetExists($offset) {
331 return in_array($offset, ['entity', 'action', 'params', 'version', 'check_permissions', 'id']) ||
isset($this->_arrayStorage
[$offset]);
337 public function &offsetGet($offset) {
339 if (in_array($offset, ['entity', 'action'])) {
342 if (in_array($offset, ['entityName', 'actionName', 'params', 'version'])) {
343 $getter = 'get' . ucfirst($offset);
344 $val = $this->$getter();
347 if ($offset == 'check_permissions') {
348 return $this->checkPermissions
;
350 if ($offset == 'id') {
353 if (isset($this->_arrayStorage
[$offset])) {
354 return $this->_arrayStorage
[$offset];
362 public function offsetSet($offset, $value) {
363 if (in_array($offset, ['entity', 'action', 'entityName', 'actionName', 'params', 'version', 'id'])) {
364 throw new \
API_Exception('Cannot modify api4 state via array access');
366 if ($offset == 'check_permissions') {
367 $this->setCheckPermissions($value);
370 $this->_arrayStorage
[$offset] = $value;
377 public function offsetUnset($offset) {
378 if (in_array($offset, ['entity', 'action', 'entityName', 'actionName', 'params', 'check_permissions', 'version', 'id'])) {
379 throw new \
API_Exception('Cannot modify api4 state via array access');
381 unset($this->_arrayStorage
[$offset]);
385 * Is this api call permitted?
387 * This function is called if checkPermissions is set to true.
390 * @internal Implement/override in civicrm-core.git only. Signature may evolve.
392 public function isAuthorized(): bool {
393 $permissions = $this->getPermissions();
394 return \CRM_Core_Permission
::check($permissions);
400 public function getPermissions() {
401 $permissions = call_user_func([CoreUtil
::getApiClass($this->_entityName
), 'permissions']);
403 // applies to getFields, getActions, etc.
404 'meta' => ['access CiviCRM'],
405 // catch-all, applies to create, get, delete, etc.
406 'default' => ['administer CiviCRM'],
408 $action = $this->getActionName();
409 // Map specific action names to more generic versions
411 'getActions' => 'meta',
412 'getFields' => 'meta',
413 'replace' => 'delete',
416 $generic = $map[$action] ??
'default';
417 return $permissions[$action] ??
$permissions[$generic] ??
$permissions['default'];
421 * Returns schema fields for this entity & action.
423 * Here we bypass the api wrapper and run the getFields action directly.
424 * This is because we DON'T want the wrapper to check permissions as this is an internal op.
425 * @see \Civi\Api4\Action\Contact\GetFields
427 * @throws \API_Exception
430 public function entityFields() {
431 if (!$this->_entityFields
) {
432 $allowedTypes = ['Field', 'Filter', 'Extra'];
433 $getFields = \Civi\API\Request
::create($this->getEntityName(), 'getFields', [
435 'checkPermissions' => FALSE,
436 'action' => $this->getActionName(),
437 'where' => [['type', 'IN', $allowedTypes]],
439 $result = new Result();
440 // Pass TRUE for the private $isInternal param
441 $getFields->_run($result, TRUE);
442 $this->_entityFields
= (array) $result->indexBy('name');
444 return $this->_entityFields
;
448 * @return \ReflectionClass
450 public function reflect() {
451 if (!$this->_reflection
) {
452 $this->_reflection
= new \
ReflectionClass($this);
454 return $this->_reflection
;
458 * Validates required fields for actions which create a new object.
462 * @throws \API_Exception
464 protected function checkRequiredFields($values) {
466 foreach ($this->entityFields() as $fieldName => $fieldInfo) {
467 if (!isset($values[$fieldName]) ||
$values[$fieldName] === '') {
468 if (!empty($fieldInfo['required']) && !isset($fieldInfo['default_value'])) {
469 $unmatched[] = $fieldName;
471 elseif (!empty($fieldInfo['required_if'])) {
472 if ($this->evaluateCondition($fieldInfo['required_if'], ['values' => $values])) {
473 $unmatched[] = $fieldName;
482 * Replaces pseudoconstants in input values
484 * @param array $record
485 * @throws \API_Exception
487 protected function formatWriteValues(&$record) {
489 // Collect fieldnames with a :pseudoconstant suffix & remove them from $record array
490 foreach (array_keys($record) as $expr) {
491 $suffix = strrpos($expr, ':');
493 $fieldName = substr($expr, 0, $suffix);
494 $field = $this->entityFields()[$fieldName] ??
NULL;
496 $optionFields[$fieldName] = [
497 'val' => $record[$expr],
500 'suffix' => substr($expr, $suffix +
1),
501 'depends' => $field['input_attrs']['control_field'] ??
NULL,
503 unset($record[$expr]);
507 // Sort option lookups by dependency, so e.g. country_id is processed first, then state_province_id, then county_id
508 uasort($optionFields, function ($a, $b) {
509 return $a['field']['name'] === $b['depends'] ?
-1 : 1;
511 // Replace pseudoconstants. Note this is a reverse lookup as we are evaluating input not output.
512 foreach ($optionFields as $fieldName => $info) {
513 $options = FormattingUtil
::getPseudoconstantList($info['field'], $info['expr'], $record, 'create');
514 $record[$fieldName] = FormattingUtil
::replacePseudoconstant($options, $info['val'], TRUE);
519 * This function is used internally for evaluating field annotations.
521 * It should never be passed raw user input.
523 * @param string $expr
524 * Conditional in php format e.g. $foo > $bar
526 * Variable name => value
528 * @throws \API_Exception
531 protected function evaluateCondition($expr, $vars) {
532 if (strpos($expr, '}') !== FALSE ||
strpos($expr, '{') !== FALSE) {
533 throw new \
API_Exception('Illegal character in expression');
535 $tpl = "{if $expr}1{else}0{/if}";
536 return (bool) trim(\CRM_Core_Smarty
::singleton()->fetchWith('string:' . $tpl, $vars));
540 * When in debug mode, this logs the callback function being used by a Basic*Action class.
542 * @param callable $callable
544 protected function addCallbackToDebugOutput($callable) {
545 if ($this->debug
&& empty($this->_debugOutput
['callback'])) {
546 if (is_scalar($callable)) {
547 $this->_debugOutput
['callback'] = (string) $callable;
549 elseif (is_array($callable)) {
550 foreach ($callable as $key => $unit) {
551 $this->_debugOutput
['callback'][$key] = is_object($unit) ?
get_class($unit) : (string) $unit;
554 elseif (is_object($callable)) {
555 $this->_debugOutput
['callback'] = get_class($callable);